Skip to content

River Run ​

Race a speed boat down an endless river. The river is generated section by section while you drive.

Steer with A D or the arrow keys, accelerate with W / Up and brake with S / Down. On touch devices drag a finger like a joystick.

Assets from various Kenney and kaylousberg asset packs.

ts
import {
  BehaviorComponent,
  CameraComponent,
  CopyRotationConstraint,
  EcsGame,
  KeyboardInputSystem,
  ModelComponent,
  ParticleEmitterComponent,
  ParticleSystem,
  SpriteComponent,
  TouchInput,
  TransformComponent,
} from '@gglib/components'
import { GameComponent, GameEntity, GameSystem, GameWorld, SystemOrder } from '@gglib/ecs'
import { Color, CommonInputs, Device, PlatformId, Texture } from '@gglib/graphics'
import { GLTF } from '@gglib/loaders'
import { clamp, lerp, vec3, vec3Normalize, vec4 } from '@gglib/math'
import { opaquePass, RenderChannel, Renderer, transparentPass } from '@gglib/render'
import { mount } from 'tweak-ui'
import { BoatComponent, BoatSystem } from './boat'
import {
  BLOCK,
  FOV,
  LIVES,
  MAX_FIT_ASPECT,
  MAX_SPEED,
  MIN_SPEED,
  MODELS,
  PARKED_Y,
  PITCH_FAST,
  PITCH_SLOW,
  POPUP_TIME,
  RIVER_SCREEN_WIDTH,
  RIVER_WIDTH,
  STATUS,
} from './constants'
import { TrafficSystem } from './obstacles'
import { rowZ } from './river'
import { RiverStreamingSystem } from './streaming'

export default (canvas: HTMLCanvasElement, tools: HTMLElement, platform: PlatformId) => {
  const game = new RiverRunGame({
    canvas,
    platform,
    autosize: true,
  })

  game.run()
  const panel = mount(tools, (ui) => {
    ui.button('Restart', { onClick: () => game.restart() })
  })

  return () => {
    game.destroy()
    panel.dispose()
  }
}

type State = keyof typeof STATUS

/**
 * A sprite of a sprite sheet: the texture and the source rectangle in pixels
 */
interface SheetSprite {
  texture: Texture
  x: number
  y: number
  width: number
  height: number
}

/**
 * An endless river race. The game wires up systems and entities and runs the race: start, game over, restart,
 * the HUD and the points of a jump. The boat, the traffic, the camera and the streaming of the river are systems.
 *
 * The update loop does not allocate: rows, obstacles and their entities are recycled, the HUD and the points of a
 * jump are created once. New objects are only created while the pools grow at the start of a race
 */
class RiverRunGame extends EcsGame {
  public readonly hud = {
    status: STATUS.ready,
    score: 0,
    speed: MIN_SPEED,
    lives: LIVES,
  }

  private state: State = 'ready'
  private overTime = 0
  private readonly cameraSystem = new RaceCameraSystem()
  private readonly streaming = new RiverStreamingSystem()
  private camera!: CameraComponent
  private boat!: BoatComponent

  // the sprites of the sprite sheets by name, and the ones the HUD uses
  private readonly sprites = new Map<string, SheetSprite>()
  private readonly digitSprites: SheetSprite[] = []
  private plusSprite!: SheetSprite
  private lifeSprite!: SheetSprite
  private lostLifeSprite!: SheetSprite
  private padSprite!: SheetSprite
  private nubSprite!: SheetSprite
  private readonly scoreDigits: SpriteComponent[] = []
  private readonly lifeIcons: SpriteComponent[] = []
  // the joystick in a bottom corner: shows the input of the keys or the finger
  private readonly joystickPad = new SpriteComponent()
  private readonly joystickNub = new SpriteComponent()
  // the digits of a number, most significant first
  private readonly digits: number[] = []
  private popup!: PopupComponent

  protected override onCreate(): void {
    this.world.addSystem(new KeyboardInputSystem({}))
    this.world.addSystem(new TouchInput({ eventTarget: this.device.canvas }))
    this.world.getSystem(TouchInput).touch.preventDefault = true
    this.world.addSystem(new BoatSystem())
    this.world.addSystem(new TrafficSystem())
    this.world.addSystem(this.cameraSystem)
    this.world.addSystem(this.streaming)
    this.world.addSystem(new ParticleSystem(this.device))
    this.world.addSystem(
      new Renderer(this.device, {
        pipeline: {
          passes: [opaquePass(), transparentPass()],
        },
        // no HDR post processing, so 8 bit color is enough and needs half the memory bandwidth
        channels: {
          [RenderChannel.Color]: { format: 'rgba8unorm' },
          [RenderChannel.ColorMsaa]: { format: 'rgba8unorm', sampleCount: 4 },
        },
      }),
    )
  }

  protected override onInitialize(): void {
    this.content.registerLoader(GLTF.Loader)

    const renderer = this.world.getSystem(Renderer)
    renderer.inputs.set(CommonInputs.Global.AmbientColor, Color.SlateGray)
    renderer.inputs.set(CommonInputs.Global.AmbientColorTop, Color.White)
    renderer.inputs.set(CommonInputs.Global.AmbientDirection, vec3Normalize(vec3(0.5, 1, -0.3)))

    this.camera = this.createEntity({
      name: 'Camera',
      parent: this.scene.entity,
      components: [new CameraComponent({ type: 'perspective', perspectiveFov: FOV, far: 400 })],
    }).$(CameraComponent)
    this.scene.setCamera(0, this.camera)

    createParticleChannels(this.world.getSystem(ParticleSystem), this.device)
    this.boat = this.createBoat()
    this.cameraSystem.follow(this.camera, this.boat)
  }

  protected override async onLoadContent() {
    await Promise.all([
      this.loadSheet('/sprites/fish.png', '/sprites/fish.sheet.json'),
      this.loadSheet('/sprites/interface.png', '/sprites/interface.sheet.json'),
      this.loadSheet('/sprites/mobile.png', '/sprites/mobile.sheet.json'),
    ])
    for (let i = 0; i < 10; i++) {
      this.digitSprites.push(this.sprites.get(`hud_number_${i}`)!)
    }
    this.plusSprite = this.sprites.get('hud_plus')!
    this.lifeSprite = this.sprites.get('minimapIcon_jewelRed')!
    this.lostLifeSprite = this.sprites.get('minimapIcon_jewelWhite')!
    this.padSprite = this.sprites.get('joystick_circle_pad_a')!
    this.nubSprite = this.sprites.get('joystick_circle_nub_a')!
    this.createHud()
    this.createPopup()
    this.restart()
  }

  private createBoat(): BoatComponent {
    const entity = this.createEntity({
      name: 'Player',
      parent: this.scene.entity,
    })
    const model = this.createEntity({
      parent: entity,
      transform: new TransformComponent({ position: vec3(0, -0.1, 0) }),
      components: [new ModelComponent()],
    })
    this.content.loadModel(MODELS.boat).then((loaded) => {
      model.$(ModelComponent).model = loaded.instantiate()
    })

    const wake = new ParticleEmitterComponent({
      channel: 'wake',
      frequency: 0,
      inheritVelocity: 0,
    })
    this.createEntity({
      name: 'wake',
      parent: entity,
      transform: new TransformComponent({ position: vec3(0, 0.1, -1.6) }),
      components: [wake],
    })

    const splash = new ParticleEmitterComponent({
      channel: 'splash',
      frequency: 0,
      inheritVelocity: 0.2,
    })
    this.createEntity({
      name: 'splash',
      parent: entity,
      transform: new TransformComponent({ position: vec3(0, 0.2, 0.5) }),
      components: [splash],
    })

    const boat = new BoatComponent(model.$(TransformComponent), wake, splash)
    entity.addComponent(boat)
    return boat
  }

  public restart() {
    this.streaming.restart(Math.floor(Math.random() * 1e9))
    this.boat.reset(0, rowZ(3))
    this.cameraSystem.reset()
    this.setState('ready')
  }

  private setState(state: State) {
    this.state = state
    this.hud.status = STATUS[state]
  }

  /**
   * Runs the race. Called before the systems update, it sees the input and the boat of the last frame
   */
  protected override onUpdate(time: number, dt: number): void {
    const boat = this.boat
    switch (this.state) {
      case 'ready':
        if (boat.throttle > 0 || boat.start) {
          boat.racing = true
          this.setState('running')
        }
        break
      case 'running':
        if (boat.lives <= 0) {
          this.overTime = 0
          this.setState('over')
        }
        break
      case 'over':
        this.overTime += dt
        if (this.overTime > 1 && boat.start) {
          this.restart()
        }
        break
    }
    if (boat.jumpPoints) {
      this.showPoints(boat.jumpPoints)
      boat.jumpPoints = 0
    }
    this.updateHud()
  }

  /**
   * Loads a sprite sheet: a texture and named source rectangles. The sheets come in two formats, a list of
   * rectangles with a name or an object with the rectangles by name
   */
  private async loadSheet(image: string, sheet: string) {
    type Rect = { x: number; y: number; width: number; height: number }
    const texture = await this.content.loadTexture(image)
    const response = await this.content.fetch<Array<Rect & { name: string }> | { sprites: Record<string, Rect> }>(
      sheet,
      { responseType: 'json' },
    )
    const body = response.body
    const rects = Array.isArray(body) ? body.map((it) => [it.name, it] as const) : Object.entries(body?.sprites ?? {})
    for (const [name, { x, y, width, height }] of rects) {
      this.sprites.set(name, { texture, x, y, width, height })
    }
  }

  private setSprite(sprite: SpriteComponent, it: SheetSprite) {
    sprite.setTexture(it.texture, it.x, it.y, it.width, it.height)
  }

  /**
   * Score digits and lives are sprites on a plane in front of the camera, so they stay on screen
   */
  private createHud() {
    const hud = this.createEntity({
      name: 'HUD',
      parent: this.camera.entity,
      // the camera looks along -z
      transform: new TransformComponent({ position: vec3(0, 0, -1) }),
    })
    for (let i = 0; i < 8; i++) {
      const sprite = new SpriteComponent()
      this.createEntity({ parent: hud, components: [sprite] })
      this.scoreDigits.push(sprite)
      this.digits.push(0)
    }
    for (let i = 0; i < LIVES; i++) {
      const sprite = new SpriteComponent()
      this.createEntity({ parent: hud, components: [sprite] })
      this.lifeIcons.push(sprite)
    }
    this.setSprite(this.joystickPad, this.padSprite)
    this.setSprite(this.joystickNub, this.nubSprite)
    this.createEntity({ parent: hud, components: [this.joystickPad] })
    this.createEntity({ parent: hud, components: [this.joystickNub] })
  }

  private updateHud() {
    const boat = this.boat
    const score = Math.floor(boat.points)
    this.hud.score = score
    this.hud.speed = Math.round(boat.speed * 10) / 10
    this.hud.lives = boat.lives

    // the HUD plane is 1 unit in front of the camera
    const halfHeight = Math.tan(FOV / 2)
    const halfWidth = halfHeight * this.device.output.aspectRatio
    const over = this.state === 'over'
    const size = halfHeight * (over ? 0.3 : 0.14)
    const advance = size * 0.62
    const count = this.toDigits(score)
    // top left while racing, centered after the game is over
    const left = over ? (-count * advance) / 2 + advance / 2 : -halfWidth + size * 0.7
    const top = over ? 0 : halfHeight - size * 0.7
    for (let i = 0; i < this.scoreDigits.length; i++) {
      const sprite = this.scoreDigits[i]
      this.setSprite(sprite, this.digitSprites[i < count ? this.digits[i] : 0])
      sprite.setSize(i < count ? size : 0)
      sprite.entity.$(TransformComponent).setPosition(left + i * advance, top, 0)
    }
    // below the score, the lost lives are white
    const icon = halfHeight * 0.09
    for (let i = 0; i < this.lifeIcons.length; i++) {
      const sprite = this.lifeIcons[i]
      this.setSprite(sprite, i < boat.lives ? this.lifeSprite : this.lostLifeSprite)
      sprite.setSize(over ? 0 : icon)
      sprite.entity.$(TransformComponent).setPosition(-halfWidth + size * 0.55 + i * icon * 1.2, top - size * 0.75, 0)
    }
    this.updateJoystick(halfWidth, halfHeight, over)
  }

  /**
   * The joystick in the bottom corner on the side of the last touch, bottom right by default. The nub shows the
   * input, of the keys or the finger
   */
  private updateJoystick(halfWidth: number, halfHeight: number, hidden: boolean) {
    const boat = this.boat
    // at most a quarter of the screen width, the HUD plane is 2 * halfWidth wide
    const pad = Math.min(halfHeight * 0.36, halfWidth * 0.5)
    const margin = Math.min(halfHeight, halfWidth) * 0.08
    const x = boat.controlSide * (halfWidth - margin - pad / 2)
    const y = -halfHeight + margin + pad / 2
    this.joystickPad.setSize(hidden ? 0 : pad)
    this.joystickPad.entity.$(TransformComponent).setPosition(x, y, 0)
    // in front of the pad, steering right moves the nub right, throttle moves it up
    const reach = pad * 0.3
    this.joystickNub.setSize(hidden ? 0 : pad * 0.5)
    this.joystickNub.entity.$(TransformComponent).setPosition(x + boat.steer * reach, y + boat.throttle * reach, 0.001)
  }

  /**
   * The points of a jump: a plus and up to three digits that face the camera. Created once and reused
   */
  private createPopup() {
    this.popup = new PopupComponent()
    const entity = this.createEntity({
      name: 'Popup',
      parent: this.scene.entity,
      transform: new TransformComponent({ position: vec3(0, PARKED_Y, 0) }),
      components: [
        new CopyRotationConstraint({
          source: this.camera.entity.$(TransformComponent),
          sourceSpace: 'world',
          targetSpace: 'world',
        }),
        this.popup,
      ],
    })
    for (let i = 0; i < 4; i++) {
      // a texture of the sheet from the start, so the glyphs share the batch of the HUD digits
      const sprite = new SpriteComponent().setSize(0)
      this.setSprite(sprite, this.plusSprite)
      this.createEntity({ parent: entity, components: [sprite] })
      this.popup.glyphs.push(sprite)
    }
  }

  /**
   * Shows the points of a jump above the boat: a plus and the digits
   */
  private showPoints(points: number) {
    const glyphs = this.popup.glyphs
    const count = this.toDigits(points)
    for (let i = 0; i < glyphs.length; i++) {
      const glyph = glyphs[i]
      if (i > count) {
        glyph.setSize(0)
        continue
      }
      this.setSprite(glyph, i === 0 ? this.plusSprite : this.digitSprites[this.digits[i - 1]])
      glyph.setSize(1.2)
      glyph.entity.$(TransformComponent).setPosition((i - count / 2) * 0.75, 0, 0)
    }
    this.popup.show(this.boat.x, this.boat.z, this.boat.speed)
  }

  /**
   * Writes the digits of a whole number into `digits`, returns their count
   */
  private toDigits(value: number) {
    const digits = this.digits
    let count = 1
    for (let rest = Math.floor(value / 10); rest > 0 && count < digits.length; rest = Math.floor(rest / 10)) {
      count++
    }
    let rest = value
    for (let i = count - 1; i >= 0; i--) {
      digits[i] = rest % 10
      rest = Math.floor(rest / 10)
    }
    return count
  }
}

// +z is the top of the screen, also when the camera looks straight down
const SCREEN_UP = vec3(0, 0, 1)

/**
 * A top down view that follows the boat. The river keeps its share of the screen width, the camera moves further
 * away on narrow screens. Screens wider than {@link MAX_FIT_ASPECT} show more scenery on the sides instead. A slow boat is near the bottom edge of the screen and the camera looks straight down,
 * at full speed the boat moves up to the center and the camera tilts forward.
 *
 * Runs after the boat moved and before the camera computes its view. Tells the streaming system which part of the
 * river is on the screen
 */
class RaceCameraSystem extends GameSystem {
  public override order: number = SystemOrder.Default + 2

  private camera!: CameraComponent
  private boat!: BoatComponent
  private streaming!: RiverStreamingSystem
  private device!: Device
  private readonly target = vec3()
  // smoothed position of the boat on the screen, 0 at the bottom when slow, 1 at the center when fast
  private screenPosition = 0

  public follow(camera: CameraComponent, boat: BoatComponent) {
    this.camera = camera
    this.boat = boat
  }

  public reset() {
    this.screenPosition = 0
  }

  public initialize(world: GameWorld): void {
    this.streaming = world.getSystem(RiverStreamingSystem)
    this.device = world.getSystem(Device)
  }

  public destroy(): void {
    //
  }

  public override update(time: number, dt: number): void {
    const aspect = this.device.output.aspectRatio
    this.camera.aspect = aspect
    const distance = RIVER_WIDTH / RIVER_SCREEN_WIDTH / (Math.tan(FOV / 2) * Math.min(aspect, MAX_FIT_ASPECT))
    // the widest part of the screen on the water: its top edge, when the camera is tilted the most. Rows are placed
    // at the top edge, so they are wide enough for any tilt
    const topDistance = (distance * Math.sin(PITCH_FAST)) / Math.sin(PITCH_FAST - FOV / 2)
    this.streaming.viewHalfWidth = topDistance * Math.sin(FOV / 2) * aspect + 2 * BLOCK

    const t = clamp((this.boat.speed - MIN_SPEED) / (MAX_SPEED - MIN_SPEED), 0, 1)
    this.screenPosition += (t - this.screenPosition) * Math.min(1, dt * 2)
    const pitch = lerp(PITCH_SLOW, PITCH_FAST, this.screenPosition)
    const height = distance * Math.sin(pitch)
    const back = distance * Math.cos(pitch)
    // the bottom and top edge of the screen on the water, relative to the point the camera looks at.
    // The ray through the bottom edge points down and backwards when the camera looks straight down
    const bottomRay = pitch + FOV / 2
    const topRay = pitch - FOV / 2
    const bottom = -back + (height * Math.cos(bottomRay)) / Math.sin(bottomRay)
    const top = -back + (height * Math.cos(topRay)) / Math.sin(topRay)
    // a slow boat is 3 units above the bottom edge, a fast boat at the center
    const focus = this.boat.z + lerp(-bottom - 3, 0, this.screenPosition)
    // follows the curves of the river
    const x = this.streaming.river.centerX(focus)

    this.target.x = x
    this.target.y = 0
    this.target.z = focus
    const transform = this.camera.entity.$(TransformComponent)
    transform.setPosition(x, height, focus - back)
    transform.lookAt(this.target, SCREEN_UP)

    this.streaming.viewBottom = focus + bottom
    this.streaming.viewTop = focus + top
  }
}

/**
 * Lets the points of a jump rise with the boat for a moment, then hides them
 */
class PopupComponent implements GameComponent, BehaviorComponent {
  public readonly entity!: GameEntity
  public readonly glyphs: SpriteComponent[] = []
  private age = POPUP_TIME
  private speed = 0

  public show(x: number, z: number, speed: number) {
    this.age = 0
    this.speed = speed
    this.entity.$(TransformComponent).setPosition(x, 2.5, z)
  }

  public updateBehavior(time: number, dt: number): void {
    if (this.age >= POPUP_TIME) {
      return
    }
    this.age += dt
    this.entity.$(TransformComponent).translate(0, dt * 2, this.speed * dt)
    if (this.age >= POPUP_TIME) {
      for (let i = 0; i < this.glyphs.length; i++) {
        this.glyphs[i].setSize(0)
      }
    }
  }
}

/**
 * The wake behind the boat and the splash after a jump or a crash
 */
function createParticleChannels(particles: ParticleSystem, device: Device) {
  // the wake spreads on the water behind the boat, the particles stay where they were emitted
  particles.addChannel('wake', {
    maxParticles: 1500,
    texture: discTexture(device),
    duration: 1.2,
    durationRandomness: 0.2,
    minColor: vec4(0.75, 0.88, 1, 0.9),
    maxColor: vec4(0.92, 0.97, 1, 0.9),
    minStartSize: 0.15,
    maxStartSize: 0.2,
    minEndSize: 0.4,
    maxEndSize: 0.55,
    minHorizontalVelocity: 0.3,
    maxHorizontalVelocity: 1.2,
    endVelocity: 0.4,
    fadeIn: 0.02,
    fadeOut: 0.5,
  })
  particles.addChannel('splash', {
    maxParticles: 500,
    texture: discTexture(device),
    duration: 0.8,
    durationRandomness: 0.3,
    minColor: vec4(0.85, 0.94, 1, 0.95),
    maxColor: vec4(1, 1, 1, 0.95),
    minStartSize: 0.15,
    maxStartSize: 0.25,
    minEndSize: 0.08,
    maxEndSize: 0.15,
    minHorizontalVelocity: 1.5,
    maxHorizontalVelocity: 3.5,
    minVerticalVelocity: 2.5,
    maxVerticalVelocity: 5,
    gravity: vec3(0, -12, 0),
    endVelocity: 0.6,
    fadeIn: 0.02,
    fadeOut: 0.3,
  })
}

/**
 * A white disc with a hard edge, for the wake and splash particles
 */
function discTexture(device: Device, size = 16) {
  const data = new Uint8Array(size * size * 4)
  const r = size / 2
  for (let y = 0; y < size; y++) {
    for (let x = 0; x < size; x++) {
      const inside = Math.hypot(x + 0.5 - r, y + 0.5 - r) <= r
      data.set([255, 255, 255, inside ? 255 : 0], (y * size + x) * 4)
    }
  }
  return device.createTexture({
    name: 'Particle Disc',
    source: data,
    width: size,
    height: size,
    format: 'rgba8unorm',
    generateMipmap: false,
  })
}
ts
import { KeyboardInputSystem, ParticleEmitterComponent, TouchInput, TransformComponent } from '@gglib/components'
import { GameComponent, GameEntity, GameQuery, GameSystem, GameWorld, SystemOrder } from '@gglib/ecs'
import { KeyboardKeys } from '@gglib/game'
import { Device } from '@gglib/graphics'
import { clamp } from '@gglib/math'
import {
  ACCELERATION,
  BLOCK,
  BOAT_HALF_X,
  BOAT_HALF_Z,
  BRAKING,
  DRAG,
  GRAVITY,
  INVULNERABLE,
  JUMP_POINTS,
  LIVES,
  MAX_SPEED,
  MIN_SPEED,
  RIVER_WIDTH,
  WATER_LEVEL,
} from './constants'
import { ObstacleComponent } from './obstacles'
import { RiverStreamingSystem } from './streaming'

/**
 * The state of the player boat
 */
export class BoatComponent implements GameComponent {
  public readonly entity!: GameEntity

  /**
   * Whether the boat races. Without racing it waits, or coasts out after the last life
   */
  public racing = false

  // input, -1 to 1
  public throttle = 0
  public steer = 0
  /**
   * Space, Enter or a new touch in this frame
   */
  public start = false
  /**
   * The side of the screen the touch controls are on, `1` right or `-1` left. A touch on the left half of the
   * screen moves them to the left
   */
  public controlSide = 1

  public x = 0
  public z = 0
  /**
   * Height above the water, greater than 0 on a ramp and in the air
   */
  public y = 0
  public speed = MIN_SPEED
  public sideSpeed = 0
  public verticalSpeed = 0
  public airTime = 0

  public lives = LIVES
  /**
   * Seconds left in which the boat passes through obstacles
   */
  public invulnerable = 0
  public points = 0
  /**
   * The points of the last jump, set when the boat lands. The game shows and resets them
   */
  public jumpPoints = 0
  /**
   * Seconds the splash emitter is on
   */
  public splashTime = 0

  public constructor(
    /**
     * The transform of the model, it tilts and blinks without moving the emitters
     */
    public readonly model: TransformComponent,
    public readonly wake: ParticleEmitterComponent,
    public readonly splash: ParticleEmitterComponent,
  ) {}

  public reset(x: number, z: number) {
    this.racing = false
    this.x = x
    this.z = z
    this.y = 0
    this.speed = MIN_SPEED
    this.sideSpeed = 0
    this.verticalSpeed = 0
    this.lives = LIVES
    this.invulnerable = 0
    this.points = 0
    this.jumpPoints = 0
  }
}

/**
 * Reads the keyboard and touch input and drives the boats: speed and steering, the shore, ramps and jumps, crashes
 * into obstacles, and how the boat leans, bobs and blinks
 */
export class BoatSystem extends GameSystem {
  public override order: number = SystemOrder.Default

  private boats!: GameQuery
  private obstacles!: GameQuery
  private keyboard!: KeyboardInputSystem
  private touch!: TouchInput
  private streaming!: RiverStreamingSystem
  private canvas!: HTMLCanvasElement
  // the finger that steers, a touch acts like a joystick relative to where it touched down
  private readonly touchStart = { active: false, id: 0, x: 0, y: 0 }

  public initialize(world: GameWorld): void {
    this.boats = world.query({ scope: 'active', required: [BoatComponent] })
    this.obstacles = world.query({ scope: 'active', required: [ObstacleComponent] })
    this.keyboard = world.getSystem(KeyboardInputSystem)
    this.touch = world.getSystem(TouchInput)
    this.streaming = world.getSystem(RiverStreamingSystem)
    this.canvas = world.getSystem(Device).canvas as HTMLCanvasElement
  }

  public destroy(): void {
    //
  }

  public override update(time: number, dt: number): void {
    dt = Math.min(dt, 0.05)
    for (const entity of this.boats) {
      const boat = entity.$(BoatComponent)
      this.readInput(boat)
      if (boat.racing) {
        this.drive(boat, dt)
      } else if (boat.lives <= 0) {
        // coasts out after the last life
        boat.speed = Math.max(0, boat.speed - 8 * dt)
        boat.z += boat.speed * dt
      }
      this.updateTransform(boat, entity.$(TransformComponent), time, dt)
    }
  }

  private readInput(boat: BoatComponent) {
    const keys = this.keyboard
    let throttle = 0
    let steer = 0
    if (keys.isPressed(KeyboardKeys.ArrowUp) || keys.isPressed(KeyboardKeys.KeyW)) {
      throttle += 1
    }
    if (keys.isPressed(KeyboardKeys.ArrowDown) || keys.isPressed(KeyboardKeys.KeyS)) {
      throttle -= 1
    }
    if (keys.isPressed(KeyboardKeys.ArrowLeft) || keys.isPressed(KeyboardKeys.KeyA)) {
      steer -= 1
    }
    if (keys.isPressed(KeyboardKeys.ArrowRight) || keys.isPressed(KeyboardKeys.KeyD)) {
      steer += 1
    }
    let start = keys.justPressed(KeyboardKeys.Space) || keys.justPressed(KeyboardKeys.Enter)

    const touch = this.touchStart
    const ids = this.touch.touchIds
    const id = touch.active && ids.includes(touch.id) ? touch.id : ids.length ? ids[0] : -1
    if (id < 0) {
      touch.active = false
    } else {
      const x = this.touch.x(id)!
      const y = this.touch.y(id)!
      if (!touch.active || touch.id !== id) {
        touch.active = true
        touch.id = id
        touch.x = x
        touch.y = y
        start = true
        // the touch coordinates are in CSS pixels of the canvas
        boat.controlSide = x < this.canvas.clientWidth / 2 ? -1 : 1
      }
      steer += clamp((x - touch.x) / 50, -1, 1)
      throttle += clamp((touch.y - y) / 50, -1, 1)
    }
    boat.throttle = clamp(throttle, -1, 1)
    boat.steer = clamp(steer, -1, 1)
    boat.start = start
  }

  private drive(boat: BoatComponent, dt: number) {
    const airborne = boat.y > 0.01 && !this.rampBelow(boat)
    if (!airborne) {
      // full throttle accelerates, braking is faster, without input the boat slowly loses speed
      const throttle = boat.throttle
      const change = throttle > 0 ? ACCELERATION * throttle : throttle < 0 ? BRAKING * throttle : -DRAG
      boat.speed = clamp(boat.speed + change * dt, MIN_SPEED, MAX_SPEED)
      // the camera looks along +z, so +x is on the left of the screen
      const target = -boat.steer * (5 + boat.speed * 0.3)
      boat.sideSpeed += (target - boat.sideSpeed) * Math.min(1, dt * 8)
    }

    const lastX = boat.x
    boat.x += boat.sideSpeed * dt
    boat.z += boat.speed * dt
    // faster driving scores more per unit of distance
    boat.points += boat.speed * dt * (1 + (2 * boat.speed) / MAX_SPEED)
    this.collideWithShore(boat, lastX, dt)
    this.updateHeight(boat, dt)
    boat.invulnerable = Math.max(0, boat.invulnerable - dt)
    if (!boat.invulnerable) {
      this.collideWithObstacles(boat)
    }
  }

  /**
   * The boat stays on the water. Scraping along the shore slows it down, so does a step of the bank where the river
   * curves, the boat is pushed aside. Driving head on into land is a crash
   */
  private collideWithShore(boat: BoatComponent, lastX: number, dt: number) {
    if (boat.y > 0.5 || !this.onLand(boat.x, boat.z)) {
      return
    }
    if (!this.onLand(lastX, boat.z)) {
      boat.x = lastX
      this.scrape(boat, dt)
      return
    }
    // a step of the bank is one block wide, push the boat towards the river center
    const direction = Math.sign(this.streaming.river.centerX(boat.z) - boat.x)
    for (let push = 0.25; push <= BLOCK; push += 0.25) {
      if (!this.onLand(boat.x + direction * push, boat.z)) {
        boat.x += direction * push
        this.scrape(boat, dt)
        return
      }
    }
    // head on, e.g. into the tip of an island: crash and move to the nearest water
    this.crash(boat)
    for (let offset = 0.5; offset < RIVER_WIDTH * 2; offset += 0.5) {
      if (!this.onLand(boat.x - offset, boat.z)) {
        boat.x -= offset
        return
      }
      if (!this.onLand(boat.x + offset, boat.z)) {
        boat.x += offset
        return
      }
    }
  }

  private scrape(boat: BoatComponent, dt: number) {
    boat.sideSpeed = 0
    boat.speed = Math.max(MIN_SPEED, boat.speed - 10 * dt)
  }

  /**
   * Whether a corner of the boat is on land
   */
  private onLand(x: number, z: number) {
    const river = this.streaming.river
    return (
      river.groundAt(x - BOAT_HALF_X, z - BOAT_HALF_Z) !== 'water' ||
      river.groundAt(x + BOAT_HALF_X, z - BOAT_HALF_Z) !== 'water' ||
      river.groundAt(x - BOAT_HALF_X, z + BOAT_HALF_Z) !== 'water' ||
      river.groundAt(x + BOAT_HALF_X, z + BOAT_HALF_Z) !== 'water'
    )
  }

  /**
   * Height of a ramp below the boat, 0 if there is none. The ramps rise along +z
   */
  private rampBelow(boat: BoatComponent): number {
    for (const entity of this.obstacles) {
      const ramp = entity.$(ObstacleComponent).data
      if (!ramp || ramp.kind !== 'ramp') {
        continue
      }
      const along = boat.z - (ramp.z - ramp.halfZ)
      if (Math.abs(boat.x - ramp.x) < ramp.halfX && along > 0 && along < ramp.halfZ * 2) {
        return (along / (ramp.halfZ * 2)) * ramp.height
      }
    }
    return 0
  }

  /**
   * Drives up the ramps, jumps off their end and falls back onto the water. A jump scores points
   */
  private updateHeight(boat: BoatComponent, dt: number) {
    const ramp = this.rampBelow(boat)
    if (ramp > 0 && ramp >= boat.y - 0.1) {
      // on the ramp, the height change gives the vertical speed when leaving it
      boat.verticalSpeed = (ramp - boat.y) / dt
      boat.y = ramp
      boat.airTime = 0
      return
    }
    if (boat.y <= 0) {
      return
    }
    boat.airTime += dt
    boat.verticalSpeed -= GRAVITY * dt
    boat.y += boat.verticalSpeed * dt
    if (boat.y <= 0) {
      boat.y = 0
      boat.verticalSpeed = 0
      boat.splashTime = 0.15
      if (boat.airTime > 0.3) {
        boat.jumpPoints = Math.round(boat.speed * JUMP_POINTS)
        boat.points += boat.jumpPoints
      }
    }
  }

  private collideWithObstacles(boat: BoatComponent) {
    for (const entity of this.obstacles) {
      const it = entity.$(ObstacleComponent).data
      if (!it || it.kind === 'ramp' || boat.y >= it.height) {
        continue
      }
      if (Math.abs(boat.x - it.x) < BOAT_HALF_X + it.halfX && Math.abs(boat.z - it.z) < BOAT_HALF_Z + it.halfZ) {
        this.crash(boat)
        return
      }
    }
  }

  /**
   * A crash costs a life and most of the speed. The boat then passes through obstacles for a while
   */
  private crash(boat: BoatComponent) {
    boat.lives--
    boat.speed = MIN_SPEED
    boat.sideSpeed = 0
    boat.invulnerable = INVULNERABLE
    boat.splashTime = 0.25
    if (boat.lives <= 0) {
      boat.racing = false
      boat.invulnerable = 0
    }
  }

  private updateTransform(boat: BoatComponent, transform: TransformComponent, time: number, dt: number) {
    const floating = boat.y <= 0.01
    const bob = floating ? Math.sin(time * 4) * 0.04 : 0
    // lean into the turn, nose up in the air
    const roll = floating ? -boat.sideSpeed * 0.03 : 0
    const pitch = floating ? -boat.speed * 0.004 : clamp(-boat.verticalSpeed * 0.05, -0.4, 0.4)
    const yaw = Math.atan2(boat.sideSpeed, Math.max(boat.speed, 1)) * 0.5
    transform.setPosition(boat.x, WATER_LEVEL + boat.y + bob, boat.z)
    boat.model.setRotationYawPitchRoll(yaw, pitch, roll)
    // blinks while invulnerable. Seen from above, a jump shows by the boat getting bigger
    const visible = boat.invulnerable === 0 || Math.floor(boat.invulnerable * 10) % 2 === 0
    boat.model.setScaleUniform(visible ? 1 + boat.y * 0.15 : 0)

    boat.wake.frequency = floating && boat.speed > 0 ? 25 + 50 * (boat.speed / MAX_SPEED) : 0
    boat.splashTime -= dt
    boat.splash.frequency = boat.splashTime > 0 ? 300 : 0
  }
}
ts
import { TransformComponent } from '@gglib/components'
import { GameComponent, GameEntity, GameQuery, GameSystem, GameWorld, SystemOrder } from '@gglib/ecs'
import type { Obstacle } from './river'
import { RiverStreamingSystem, type Placement } from './streaming'

/**
 * An obstacle on the river. The entities are recycled: an unused obstacle has no `data`
 */
export class ObstacleComponent implements GameComponent {
  public readonly entity!: GameEntity
  /**
   * The generated obstacle, `null` while the entity waits in the pool
   */
  public data: Obstacle | null = null
  /**
   * The models of the obstacle
   */
  public readonly placement: Placement = { entities: [], models: [], count: 0 }

  /**
   * Moves the obstacle and its models
   */
  public moveTo(x: number, z: number) {
    const data = this.data!
    data.x = x
    data.z = z
    for (let i = 0; i < this.placement.count; i++) {
      const part = data.parts[i]
      this.placement.entities[i].$(TransformComponent).setPosition(x + part.x, part.y, z + part.z)
    }
  }
}

/**
 * Drives the slow boats on the river once they come close to the screen. They keep their distance to the river
 * center where the river curves, and stop behind obstacles in their way
 */
export class TrafficSystem extends GameSystem {
  public override order: number = SystemOrder.Default + 1

  private query!: GameQuery
  private streaming!: RiverStreamingSystem

  public initialize(world: GameWorld): void {
    this.query = world.query({ scope: 'active', required: [ObstacleComponent] })
    this.streaming = world.getSystem(RiverStreamingSystem)
  }

  public destroy(): void {
    //
  }

  public override update(time: number, dt: number): void {
    const river = this.streaming.river
    if (!river) {
      return
    }
    const start = this.streaming.viewTop + 30
    for (const entity of this.query) {
      const obstacle = entity.$(ObstacleComponent)
      const boat = obstacle.data
      if (!boat || boat.kind !== 'boat' || boat.z > start || this.isBlocked(boat)) {
        continue
      }
      const z = boat.z + boat.speed * dt
      obstacle.moveTo(boat.lane + river.centerX(z), z)
    }
  }

  /**
   * Whether an obstacle is right in front of a boat. Called while the query is iterated, a query can't be iterated
   * twice at the same time, so this goes through the list of the streaming system
   */
  private isBlocked(boat: Obstacle) {
    const obstacles = this.streaming.obstacles
    for (let i = 0; i < obstacles.length; i++) {
      const it = obstacles[i].data
      if (
        it &&
        it !== boat &&
        it.kind !== 'ramp' &&
        Math.abs(it.x - boat.x) < it.halfX + boat.halfX &&
        it.z > boat.z &&
        it.z - boat.z < it.halfZ + boat.halfZ + 1
      ) {
        return true
      }
    }
    return false
  }
}
ts
import { ContentLoader } from '@gglib/content'
import { EcsGame, ModelComponent, TransformComponent } from '@gglib/components'
import { GameEntity, GameSystem, GameWorld, SystemOrder } from '@gglib/ecs'
import type { Model } from '@gglib/model'
import { BLOCK, COLUMNS, MAX_LEVEL, MODELS, PARKED_Y, WATER_LEVEL } from './constants'
import { ObstacleComponent } from './obstacles'
import { type Ground, type PartList, River, type Row, rowZ } from './river'

/**
 * The entities placed for a row or an obstacle, they go back to the pool together
 */
export interface Placement {
  entities: GameEntity[]
  models: string[]
  count: number
}

interface SpawnedRow extends Placement {
  index: number
}

/**
 * The block model of the ground at a level of a column: sand, grass on top, snow on the highest hills, dirt below
 */
function groundModel(ground: Ground, top: number, level: number) {
  if (ground === 'sand') {
    return MODELS.sand
  }
  if (level < top) {
    return MODELS.dirt
  }
  return top >= MAX_LEVEL ? MODELS.snow : MODELS.grass
}

/**
 * Streams the river: places the rows and obstacles that come into view at the top of the screen and returns those
 * that left the screen at the bottom.
 *
 * Nothing is created or destroyed while racing: every model placement is an entity that is reused for the same
 * model, unused entities are parked below the scene. Obstacles are entities with an {@link ObstacleComponent},
 * they are recycled as well. Each model is loaded once, the renderer draws all its entities as instances
 */
export class RiverStreamingSystem extends GameSystem {
  // after the camera moved, so the rows match the screen
  public override order: number = SystemOrder.Default + 3

  /**
   * The generated river
   */
  public readonly river = new River(0)
  /**
   * The obstacles on the river
   */
  public readonly obstacles: ObstacleComponent[] = []
  /**
   * The z of the bottom and top edge of the screen on the water, set by the camera
   */
  public viewBottom = 0
  public viewTop = 0
  /**
   * Half width of the scenery on the screen, from the center of the river. Columns further out are not placed
   */
  public viewHalfWidth = Infinity

  private world!: GameWorld
  private content!: ContentLoader
  private scene!: GameEntity
  private readonly models = new Map<string, Promise<Model>>()
  // unused entities by model, unused rows and unused obstacles
  private readonly modelPool = new Map<string, GameEntity[]>()
  private readonly rowPool: SpawnedRow[] = []
  private readonly obstaclePool: ObstacleComponent[] = []
  private readonly rows: SpawnedRow[] = []
  private nextRow = 0
  private fillView = false

  public initialize(world: GameWorld): void {
    this.world = world
    this.content = world.getSystem(ContentLoader)
    this.scene = world.getSystem(EcsGame).scene.entity
  }

  public destroy(): void {
    //
  }

  /**
   * Starts a new river. The rows and obstacles of the old one go back to the pools
   */
  public restart(seed: number) {
    while (this.rows.length) {
      this.releaseRow(this.rows.pop()!)
    }
    while (this.obstacles.length) {
      this.releaseObstacle(this.obstacles.pop()!)
    }
    this.river.restart(seed)
    this.nextRow = 0
    // everything in view at once on the next update, later rows are spawned a few per frame
    this.fillView = true
  }

  public override update(): void {
    this.spawn(this.fillView ? Infinity : 4)
    this.fillView = false
    this.despawn()
  }

  /**
   * Places the rows and obstacles that come into view, at most `maxRows` rows
   */
  private spawn(maxRows: number) {
    // a bit beyond the top edge of the screen, so tall models don't pop in
    const limit = this.viewTop + 3 * BLOCK
    for (let spawned = 0; spawned < maxRows && rowZ(this.nextRow) < limit; spawned++) {
      this.river.ensure(this.nextRow + 1)
      this.spawnRow(this.river.row(this.nextRow)!)
      this.nextRow++
    }
    const pending = this.river.obstacles
    while (pending.length && pending[0].z < rowZ(this.nextRow)) {
      const obstacle = this.obstaclePool.pop() ?? this.createObstacle()
      obstacle.data = pending.shift()!
      this.placeParts(obstacle.placement, obstacle.data, obstacle.data.x, obstacle.data.z)
      this.obstacles.push(obstacle)
    }
  }

  /**
   * A row of blocks. Land is a stack of blocks up to its level, with dirt below the top block. Only the blocks
   * that can be seen are placed: from the top down to the lowest neighbor
   */
  private spawnRow(row: Row) {
    const spawned = this.rowPool.pop() ?? { entities: [], models: [], count: 0, index: 0 }
    spawned.index = row.index
    const z = rowZ(row.index)
    const river = this.river
    for (let i = 0; i < COLUMNS; i++) {
      if (Math.abs(i - COLUMNS / 2 + 0.5) * BLOCK > this.viewHalfWidth) {
        continue
      }
      const { ground, level } = row.cells[i]
      const column = i - COLUMNS / 2 + row.offset
      const x = (column + 0.5) * BLOCK
      if (ground === 'water') {
        this.place(spawned, MODELS.water, x, WATER_LEVEL - BLOCK / 2, z)
        continue
      }
      const lowest = Math.min(
        river.levelAt(column - 1, row.index),
        river.levelAt(column + 1, row.index),
        river.levelAt(column, row.index - 1),
        river.levelAt(column, row.index + 1),
      )
      for (let k = Math.min(level, lowest + 1); k <= level; k++) {
        this.place(spawned, groundModel(ground, level, k), x, k * BLOCK - BLOCK / 2, z)
      }
    }
    // the decoration outside of the screen as well
    this.placeParts(spawned, row, 0, z, row.offset * BLOCK)
    this.rows.push(spawned)
  }

  /**
   * Returns the rows and obstacles below the bottom edge of the screen to the pools
   */
  private despawn() {
    const behind = this.viewBottom - 2 * BLOCK
    while (this.rows.length && rowZ(this.rows[0].index) < behind) {
      this.releaseRow(this.rows.shift()!)
    }
    // keeps the order of the remaining obstacles
    let kept = 0
    for (let i = 0; i < this.obstacles.length; i++) {
      const obstacle = this.obstacles[i]
      if (obstacle.data!.z < behind - 4) {
        this.releaseObstacle(obstacle)
      } else {
        this.obstacles[kept++] = obstacle
      }
    }
    this.obstacles.length = kept
  }

  private releaseRow(row: SpawnedRow) {
    this.release(row)
    this.rowPool.push(row)
  }

  private releaseObstacle(obstacle: ObstacleComponent) {
    this.release(obstacle.placement)
    this.river.release(obstacle.data!)
    obstacle.data = null
    this.obstaclePool.push(obstacle)
  }

  private createObstacle(): ObstacleComponent {
    return this.world
      .createEntity({
        name: 'Obstacle',
        parent: this.scene,
        transform: new TransformComponent(),
        components: [new ObstacleComponent()],
      })
      .$(ObstacleComponent)
  }

  /**
   * Places the parts of a row or an obstacle, relative to a position. With a `centerX`, parts further than the view
   * half width from it are skipped
   */
  private placeParts(placement: Placement, list: PartList, x: number, z: number, centerX?: number) {
    for (let i = 0; i < list.partCount; i++) {
      const part = list.parts[i]
      if (centerX != null && Math.abs(part.x - centerX) > this.viewHalfWidth) {
        continue
      }
      this.place(placement, part.model, x + part.x, part.y, z + part.z, part.yaw, part.scale)
    }
  }

  /**
   * Places a model, takes an unused entity of the pool if there is one
   */
  private place(placement: Placement, model: string, x: number, y: number, z: number, yaw = 0, scale = 1) {
    const entity = this.pool(model).pop() ?? this.createModelEntity(model)
    const transform = entity.$(TransformComponent)
    transform.setPosition(x, y, z)
    transform.setRotationAxisAngle(0, 1, 0, yaw)
    transform.setScaleUniform(scale)
    placement.entities[placement.count] = entity
    placement.models[placement.count] = model
    placement.count++
  }

  /**
   * Parks the entities of a placement below the scene and returns them to the pool
   */
  private release(placement: Placement) {
    for (let i = 0; i < placement.count; i++) {
      const entity = placement.entities[i]
      entity.$(TransformComponent).setPosition(0, PARKED_Y, 0)
      this.pool(placement.models[i]).push(entity)
    }
    placement.count = 0
  }

  private pool(model: string): GameEntity[] {
    let pool = this.modelPool.get(model)
    if (!pool) {
      pool = []
      this.modelPool.set(model, pool)
    }
    return pool
  }

  private createModelEntity(url: string): GameEntity {
    const entity = this.world.createEntity({
      parent: this.scene,
      transform: new TransformComponent(),
      components: [new ModelComponent()],
    })
    let model = this.models.get(url)
    if (!model) {
      model = this.content.loadModel(url)
      this.models.set(url, model)
    }
    model.then((loaded) => {
      if (!entity.isDestroyed) {
        entity.$(ModelComponent).model = loaded.instantiate()
      }
    })
    return entity
  }
}
ts
import { fbm, perlin } from '@gglib/noise'
import {
  BLOCK,
  CARGO,
  COLUMNS,
  CONTAINERS,
  INNER_LANES,
  LANE_COLUMNS,
  LANES,
  LOW_TRAFFIC,
  MAX_LEVEL,
  MODELS,
  PROPS,
  RIVER_HALF,
  RIVER_WIDTH,
  ROW_CAPACITY,
  STONES,
  TRAFFIC,
  WATER_LEVEL,
} from './constants'

export type Ground = 'water' | 'sand' | 'grass'

export interface Cell {
  ground: Ground
  /**
   * Level of the top of the ground in blocks, its top is at `level * BLOCK`. Water and sand are at level 0
   */
  level: number
}

/**
 * A model placed relative to the center of an obstacle, or in world space for a row
 */
export interface Part {
  model: string
  x: number
  y: number
  z: number
  yaw: number
  scale: number
}

/**
 * A list of parts. The part objects are reused, only the first `partCount` are in use
 */
export interface PartList {
  parts: Part[]
  partCount: number
}

export interface Row extends PartList {
  index: number
  /**
   * The river center of this row in columns, the cells are centered on it
   */
  offset: number
  /**
   * The ground of each column, from left (-x) to right (+x)
   */
  cells: Cell[]
}

export type ObstacleKind = 'boat' | 'stones' | 'island' | 'piles' | 'container' | 'cargo' | 'buoy' | 'ramp'

export interface Obstacle extends PartList {
  kind: ObstacleKind
  x: number
  z: number
  /**
   * Half extents of the collision rectangle on the water
   */
  halfX: number
  halfZ: number
  /**
   * A boat in the air passes above an obstacle that is lower than this. Ramps: height of the high end
   */
  height: number
  /**
   * Speed along +z, only for boats
   */
  speed: number
  /**
   * Distance from the river center, the boats keep it when the river curves
   */
  lane: number
}

/**
 * Center z of a row
 */
export function rowZ(index: number): number {
  return (index + 0.5) * BLOCK
}

// a small seeded random generator (mulberry32), the same seed builds the same river
function random(seed: number) {
  let state = seed >>> 0
  return () => {
    state = (state + 0x6d2b79f5) >>> 0
    let t = state
    t = Math.imul(t ^ (t >>> 15), t | 1)
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

function createRow(): Row {
  const cells: Cell[] = []
  for (let i = 0; i < COLUMNS; i++) {
    cells.push({ ground: 'water', level: 0 })
  }
  return { index: -1, offset: 0, cells, parts: [], partCount: 0 }
}

/**
 * Adds a part to a list, reuses a part object of an earlier use of the list
 */
function addPart(list: PartList, model: string, x: number, y: number, z: number, yaw = 0, scale = 1) {
  let part = list.parts[list.partCount]
  if (!part) {
    part = { model, x, y, z, yaw, scale }
    list.parts.push(part)
  }
  list.partCount++
  part.model = model
  part.x = x
  part.y = y
  part.z = z
  part.yaw = yaw
  part.scale = scale
}

/**
 * Generates the river procedurally, section by section. Rows and obstacles are only data, the game turns them
 * into entities when they come into view.
 *
 * The course of the river and the height of the land are noise fields, so they are known for any position
 * before the rows are generated.
 *
 * Rows live in a ring buffer and obstacles are recycled, so a running game does not allocate new objects
 */
export class River {
  /**
   * Obstacles that are not spawned yet, ordered by z
   */
  public readonly obstacles: Obstacle[] = []
  /**
   * Number of generated rows
   */
  public length = 0

  private readonly ring: Row[] = []
  private readonly pool: Obstacle[] = []
  private readonly course = perlin()
  private readonly hills = perlin().pipe(fbm({ octaves: 3 }))
  private rand!: () => number
  private noiseZ = 0

  public constructor(seed: number) {
    for (let i = 0; i < ROW_CAPACITY; i++) {
      this.ring.push(createRow())
    }
    this.restart(seed)
  }

  /**
   * Starts a new river, the rows and obstacles of the old one are reused
   */
  public restart(seed: number) {
    this.rand = random(seed)
    // moves the noise to another place for every seed
    this.noiseZ = (seed % 997) + 0.5
    for (const row of this.ring) {
      row.index = -1
    }
    while (this.obstacles.length) {
      this.release(this.obstacles.pop()!)
    }
    this.length = 0
    // a calm start without obstacles, then open water with a few obstacles
    this.open(16, 0)
    this.open(12, 0.1)
  }

  /**
   * The row with the given index, `null` if it is not generated or was overwritten
   */
  public row(index: number): Row | null {
    const row = this.ring[((index % ROW_CAPACITY) + ROW_CAPACITY) % ROW_CAPACITY]
    return row.index === index ? row : null
  }

  /**
   * Returns an obstacle that is not used any more, for the next sections
   */
  public release(obstacle: Obstacle) {
    obstacle.partCount = 0
    this.pool.push(obstacle)
  }

  /**
   * The center of the river at a position along the course. It runs straight at the start and curves later on
   */
  public centerX(z: number): number {
    const fadeIn = Math.min(1, Math.max(0, (z - 40) / 80))
    return this.course.sample(z * 0.012, 0.5, this.noiseZ) * 16 * fadeIn
  }

  /**
   * The river center of a row in columns. The banks move by whole blocks
   */
  public rowOffset(row: number): number {
    return Math.round(this.centerX(rowZ(row)) / BLOCK)
  }

  /**
   * The level of the land in a column of a row: hills from a noise field that rise with the distance to the river.
   * Water, sand and islands are at level 0
   */
  public levelAt(column: number, row: number): number {
    // distance in blocks from the outer edge of the sand
    const distance = Math.abs(column - this.rowOffset(row) + 0.5) - 0.5 - (RIVER_HALF + 1)
    if (distance < 0) {
      return 0
    }
    const noise = this.hills.sample(column * 0.17, row * 0.17, this.noiseZ)
    const level = Math.round(noise * 3 + Math.min(distance, 5) * 0.3)
    // no cliffs next to the sand
    const max = distance < 1 ? 1 : MAX_LEVEL
    return Math.max(0, Math.min(max, level))
  }

  /**
   * Generates sections until the river has at least the given number of rows
   */
  public ensure(rows: number) {
    while (this.length < rows) {
      // obstacles get denser and walls lose their gap over the first 400 rows
      const difficulty = Math.min(1, this.length / 400)
      // calm water between the sections, a bit less later on
      for (let i = Math.round(5 - difficulty * 2); i > 0; i--) {
        this.addRow()
      }
      const pick = this.rand()
      if (pick < 0.35) {
        this.open(16 + this.int(8), difficulty)
      } else if (pick < 0.5) {
        this.islandSplit(difficulty)
      } else if (pick < 0.65) {
        this.buoySplit(difficulty)
      } else if (pick < 0.82) {
        this.rampWall(difficulty)
      } else {
        this.traffic(difficulty)
      }
    }
  }

  /**
   * The ground at a position, rows that are not generated or already overwritten are open water
   */
  public groundAt(x: number, z: number): Ground {
    const index = Math.floor(z / BLOCK)
    const row = this.row(index)
    const offset = row ? row.offset : this.rowOffset(index)
    if (!row) {
      return Math.abs(x - offset * BLOCK) < RIVER_WIDTH ? 'water' : 'grass'
    }
    const column = Math.floor(x / BLOCK) - offset + COLUMNS / 2
    return column >= 0 && column < COLUMNS ? row.cells[column].ground : 'grass'
  }

  private int(max: number) {
    return Math.floor(this.rand() * max)
  }

  private pick<T>(items: readonly T[]): T {
    return items[this.int(items.length)]
  }

  /**
   * Adds a row. Columns closer to the river center than `island` blocks are land, an island splits the river.
   * The island is sand at its ends
   */
  private addRow(island = 0, islandSand = false): Row {
    const index = this.length++
    const row = this.ring[index % ROW_CAPACITY]
    row.index = index
    row.offset = this.rowOffset(index)
    row.partCount = 0
    for (let c = 0; c < COLUMNS; c++) {
      const block = Math.abs(c - COLUMNS / 2 + 0.5) + 0.5
      let ground: Ground = 'grass'
      if (block <= island) {
        ground = islandSand ? 'sand' : 'grass'
      } else if (block <= RIVER_HALF) {
        ground = 'water'
      } else if (block <= RIVER_HALF + 1) {
        ground = 'sand'
      }
      const cell = row.cells[c]
      cell.ground = ground
      cell.level = this.levelAt(c - COLUMNS / 2 + row.offset, index)
    }
    this.decorateShore(row)
    return row
  }

  /**
   * Center x of a column of a row in world space
   */
  private cellX(row: Row, column: number) {
    return (column - COLUMNS / 2 + row.offset + 0.5) * BLOCK
  }

  /**
   * Trees on the grass and props on the shore, standing on the ground of their column
   */
  private decorateShore(row: Row) {
    for (let column = 0; column < COLUMNS; column++) {
      const cell = row.cells[column]
      const x = this.cellX(row, column)
      const top = cell.level * BLOCK
      if (cell.ground === 'grass' && this.rand() < 0.07) {
        this.tree(row, x, top)
      } else if (cell.ground !== 'water' && this.rand() < 0.025) {
        // a block on the ground
        addPart(row, this.pick(PROPS), x, top + BLOCK / 2, 0)
      } else if (cell.ground === 'sand' && this.rand() < 0.02) {
        // a blue container on the shore, lengthwise
        addPart(row, MODELS.containerBlue, x, top, 0)
      }
    }
  }

  /**
   * A tree: a trunk of two thin wood blocks and a block of leaves
   */
  private tree(list: PartList, x: number, top: number) {
    addPart(list, MODELS.wood, x, top + 0.5, 0, 0, 0.5)
    addPart(list, MODELS.wood, x, top + 1.5, 0, 0, 0.5)
    addPart(list, top >= MAX_LEVEL * BLOCK ? MODELS.treeSnow : MODELS.tree, x, top + 3, 0)
  }

  /**
   * Adds an obstacle in a lane of the row at z, keeps the list ordered by z
   */
  private addObstacle(
    kind: ObstacleKind,
    lane: number,
    z: number,
    halfX: number,
    halfZ: number,
    height: number,
    speed = 0,
  ): Obstacle {
    const obstacle =
      this.pool.pop() ??
      ({ kind, x: 0, z: 0, halfX: 0, halfZ: 0, height: 0, speed: 0, lane: 0, parts: [], partCount: 0 } as Obstacle)
    obstacle.kind = kind
    obstacle.lane = lane
    // the river center of the row the obstacle is in
    obstacle.x = this.rowOffset(Math.floor(z / BLOCK)) * BLOCK + lane
    obstacle.z = z
    obstacle.halfX = halfX
    obstacle.halfZ = halfZ
    obstacle.height = height
    obstacle.speed = speed
    obstacle.partCount = 0
    const list = this.obstacles
    list.push(obstacle)
    for (let i = list.length - 1; i > 0 && list[i - 1].z > z; i--) {
      list[i] = list[i - 1]
      list[i - 1] = obstacle
    }
    return obstacle
  }

  /**
   * Open water with obstacles in some lanes, at least one lane stays free
   */
  private open(rows: number, difficulty: number) {
    const start = this.length
    for (let i = 0; i < rows; i++) {
      this.addRow()
    }
    if (difficulty === 0) {
      return
    }
    // rows between two rows of obstacles, a bit less later on
    const spacing = Math.round(8 - difficulty * 2)
    for (let index = start + 2; index < start + rows - 1; index += spacing + this.int(2)) {
      // one lane, sometimes a second, different one
      const first = this.int(LANES.length)
      this.landmark(LANES[first], rowZ(index))
      if (this.rand() < 0.3 + difficulty * 0.4) {
        this.landmark(LANES[(first + 1 + this.int(LANES.length - 1)) % LANES.length], rowZ(index))
      }
    }
  }

  /**
   * One of the static obstacles in a lane. Blocks stand on one of the two columns of the lane
   */
  private landmark(lane: number, z: number) {
    const column = this.pick(LANE_COLUMNS[lane])
    const pick = this.rand()
    if (pick < 0.22) {
      // a stone block sticking out of the water, sometimes two on top of each other
      const it = this.addObstacle('stones', column, z, 1, 1, 2)
      addPart(it, this.pick(STONES), 0, 0, 0)
      if (this.rand() < 0.5) {
        addPart(it, MODELS.stone, 0, BLOCK, 0)
      }
    } else if (pick < 0.38) {
      // a tiny island with a tree
      const it = this.addObstacle('island', column, z, 1, 1, 3)
      addPart(it, MODELS.grass, 0, -1, 0)
      this.tree(it, 0, 0)
    } else if (pick < 0.55) {
      // a mooring pile of wood blocks
      const it = this.addObstacle('piles', column, z, 1, 1, 3)
      addPart(it, MODELS.wood, 0, 0, 0)
      addPart(it, MODELS.wood, 0, BLOCK, 0)
    } else if (pick < 0.8) {
      // a floating container, lengthwise or across
      const across = this.rand() < 0.5
      const it = this.addObstacle('container', lane, z, across ? 1.4 : 0.7, across ? 0.7 : 1.4, 0.8)
      addPart(it, this.pick(CONTAINERS), 0, WATER_LEVEL - 0.3, 0, across ? Math.PI / 2 : 0)
    } else {
      const it = this.addObstacle('cargo', lane, z, 1.3, 1.4, 0.9)
      addPart(it, this.pick(CARGO), 0, WATER_LEVEL - 0.3, 0)
    }
  }

  /**
   * An island splits the river into two arms
   */
  private islandSplit(difficulty: number) {
    this.addRow()
    const rows = 8 + this.int(5)
    const start = this.length
    for (let i = 0; i < rows; i++) {
      const end = i === 0 || i === rows - 1
      const row = this.addRow(1, end)
      if (!end && i % 3 === 1) {
        // a tree on the island, in its left column
        this.tree(row, this.cellX(row, COLUMNS / 2 - 1), 0)
      }
    }
    this.addRow()
    // something in one of the arms
    if (this.rand() < 0.4 + difficulty * 0.5) {
      this.landmark(this.rand() < 0.5 ? -6 : 6, rowZ(start + 2 + this.int(rows - 4)))
    }
  }

  /**
   * A line of buoys splits the river, one side is blocked further ahead
   */
  private buoySplit(difficulty: number) {
    this.addRow()
    const rows = 14
    const start = this.length
    for (let i = 0; i < rows; i++) {
      this.addRow()
    }
    for (let z = rowZ(start); z < rowZ(start + rows - 1); z += 3) {
      const it = this.addObstacle('buoy', 0, z, 0.45, 0.45, 1.2)
      addPart(it, z === rowZ(start) ? MODELS.buoyFlag : MODELS.buoy, 0, WATER_LEVEL, 0)
    }
    const side = this.rand() < 0.5 ? -1 : 1
    this.landmark(side * this.pick(INNER_LANES), rowZ(start + 5))
    if (this.rand() < difficulty) {
      this.landmark(-side * this.pick(INNER_LANES), rowZ(start + 11))
    }
  }

  /**
   * A wall of containers across the river with a ramp in front of it. Early walls have a gap at the shore
   */
  private rampWall(difficulty: number) {
    this.addRow()
    const start = this.length
    for (let i = 0; i < 7; i++) {
      this.addRow()
    }
    const gapSide = this.rand() < 1 - difficulty * 0.7 ? (this.rand() < 0.5 ? -1 : 1) : 0
    const wallZ = rowZ(start + 4)
    // six containers lie across, 2.8 wide each. A gap of one container at the shore, if any
    for (let i = 0; i < 6; i++) {
      if (gapSide && (gapSide < 0 ? i === 0 : i === 5)) {
        continue
      }
      const it = this.addObstacle('container', (i - 2.5) * 2.8, wallZ, 1.4, 0.7, 0.8)
      addPart(it, this.pick(CONTAINERS), 0, WATER_LEVEL - 0.3, 0, Math.PI / 2)
    }
    // the high end of the ramp is 2 units before the wall
    const wide = this.rand() < 1 - difficulty * 0.5
    const halfX = wide ? 2.57 : 1.36
    const lane = (this.rand() - 0.5) * 2 * (RIVER_WIDTH - halfX - 1.5)
    const it = this.addObstacle('ramp', lane, wallZ - 0.7 - 2 - 1.41, halfX, 1.41, 1.14)
    addPart(it, wide ? MODELS.rampWide : MODELS.ramp, 0, WATER_LEVEL, 0)
  }

  /**
   * Slow boats ahead, they block lanes for a while
   */
  private traffic(difficulty: number) {
    const start = this.length
    const rows = 20
    for (let i = 0; i < rows; i++) {
      this.addRow()
    }
    const count = 2 + Math.round(difficulty * 2)
    // a different lane for each boat
    const firstLane = this.int(LANES.length)
    for (let i = 0; i < count; i++) {
      const model = this.int(TRAFFIC.length)
      const lane = LANES[(firstLane + i) % LANES.length] + (this.rand() - 0.5)
      const z = rowZ(start + 2 + i * 4 + this.int(2))
      const height = model < LOW_TRAFFIC ? 0.8 : 1.5
      const it = this.addObstacle('boat', lane, z, 0.9, 1.8, height, 1 + this.rand() * 1.5)
      addPart(it, TRAFFIC[model], 0, WATER_LEVEL, 0)
    }
  }
}
ts
import { DEGREE_TO_RAD } from '@gglib/math'

// ---------------------------------------------------------------------------
// the player boat
// ---------------------------------------------------------------------------

export const LIVES = 3
export const MIN_SPEED = 5
export const MAX_SPEED = 22
/**
 * Acceleration with full throttle, deceleration when braking and without input, in units per second²
 */
export const ACCELERATION = 9
export const BRAKING = 16
export const DRAG = 1.5
/**
 * Half extents of the collision rectangle of the player boat, a bit smaller than the model
 */
export const BOAT_HALF_X = 0.7
export const BOAT_HALF_Z = 1.4
/**
 * Seconds after a crash in which the boat passes through obstacles
 */
export const INVULNERABLE = 2
export const GRAVITY = 18
/**
 * Points of a jump per unit of speed
 */
export const JUMP_POINTS = 10

// ---------------------------------------------------------------------------
// camera and screen
// ---------------------------------------------------------------------------

export const FOV = 50 * DEGREE_TO_RAD
/**
 * Elevation of the camera view: straight down when slow, tilted forward a little at full speed
 */
export const PITCH_SLOW = 90 * DEGREE_TO_RAD
export const PITCH_FAST = 45 * DEGREE_TO_RAD
/**
 * Share of the screen width that the river covers, up to {@link MAX_FIT_ASPECT}
 */
export const RIVER_SCREEN_WIDTH = 1 / 2.2
/**
 * Up to this aspect ratio the camera keeps the river at its share of the screen width. Wider screens use the camera
 * distance of this aspect and show more scenery on the sides, instead of moving closer and showing less ahead
 */
export const MAX_FIT_ASPECT = 16 / 9
/**
 * Seconds the points of a jump are shown
 */
export const POPUP_TIME = 1.2

export const STATUS = {
  ready: 'Press Up or touch to start',
  running: 'Racing',
  over: 'Game over. Press Space or touch to restart',
}

// ---------------------------------------------------------------------------
// the river
// ---------------------------------------------------------------------------

/**
 * Size of a block model, the models span -1 to 1. The scenery is a grid of blocks, a row of the river is one block
 * deep. Blocks are not scaled or rotated, only the tree trunks are thinner
 */
export const BLOCK = 2
/**
 * Height of the water surface, the top of the ground blocks at level 0 is at 0
 */
export const WATER_LEVEL = -0.2
/**
 * Half width of the river in blocks, the boats race along +z
 */
export const RIVER_HALF = 4
/**
 * Half width of the river in world units
 */
export const RIVER_WIDTH = RIVER_HALF * BLOCK
/**
 * Columns of a row: grass, sand, the river, sand, grass. They move with the river when it curves.
 * Wide enough for ultra wide screens, only the columns on the screen are placed
 */
export const SHORE_COLUMNS = 20
export const COLUMNS = 2 * (RIVER_HALF + SHORE_COLUMNS)
/**
 * Highest level of the hills, in blocks. The land never goes below level 0
 */
export const MAX_LEVEL = 2
/**
 * Rows that are kept in memory. The game only needs the rows on the screen and a section ahead
 */
export const ROW_CAPACITY = 256
/**
 * Lanes of the river, relative to its center. Obstacles are placed in lanes, so there is always a way around them
 */
export const LANES = [-6, -2, 2, 6]
export const INNER_LANES = [2, 6]
/**
 * The two columns of each lane, blocks are placed on them
 */
export const LANE_COLUMNS: Record<number, [number, number]> = { [-6]: [-7, -5], [-2]: [-3, -1], 2: [1, 3], 6: [5, 7] }
/**
 * Unused entities wait far below the scene, outside of the view
 */
export const PARKED_Y = -1000

// ---------------------------------------------------------------------------
// models
// ---------------------------------------------------------------------------

const BLOCKS = '/models/gltf/blocks/'
const WATERCRAFT = '/models/gltf/watercraft/'

/**
 * The models of the river. Paths are built once, the generator only passes them around
 */
export const MODELS = {
  water: `${BLOCKS}water.gltf`,
  sand: `${BLOCKS}sand_A.gltf`,
  grass: `${BLOCKS}grass.gltf`,
  snow: `${BLOCKS}grass_with_snow.gltf`,
  dirt: `${BLOCKS}dirt.gltf`,
  wood: `${BLOCKS}wood.gltf`,
  tree: `${BLOCKS}tree.gltf`,
  treeSnow: `${BLOCKS}tree_with_snow.gltf`,
  stone: `${BLOCKS}stone.gltf`,
  stoneDark: `${BLOCKS}stone_dark.gltf`,
  boat: `${WATERCRAFT}boat-speed-a.glb`,
  buoy: `${WATERCRAFT}buoy.glb`,
  buoyFlag: `${WATERCRAFT}buoy-flag.glb`,
  ramp: `${WATERCRAFT}ramp.glb`,
  rampWide: `${WATERCRAFT}ramp-wide.glb`,
  // the blue container can't be seen on the water, it only lies on land
  containerBlue: `${WATERCRAFT}cargo-container-b.glb`,
}
export const PROPS = ['crate', 'barrel', 'hay_bale', 'stone', 'stone_dark', 'melon'].map((it) => `${BLOCKS}${it}.gltf`)
export const STONES = [MODELS.stone, MODELS.stoneDark]
export const CONTAINERS = ['cargo-container-a', 'cargo-container-c'].map((it) => `${WATERCRAFT}${it}.glb`)
export const CARGO = ['cargo-pile-a', 'cargo-pile-b'].map((it) => `${WATERCRAFT}${it}.glb`)
export const TRAFFIC = ['boat-row-small', 'boat-row-large', 'boat-fishing-small', 'boat-tug-a', 'boat-sail-a'].map(
  (it) => `${WATERCRAFT}${it}.glb`,
)
/**
 * The first traffic models are row boats, they are low and a jump passes above them
 */
export const LOW_TRAFFIC = 2

Released under the MIT License.