Code Sketch


yoii game 3d
By: Mhalsakant School
Category: Programming
import java.awt.{Color, Dimension, Font, GradientPaint, Graphics, Graphics2D, Polygon, RenderingHints, Toolkit}
import java.awt.event.{ActionEvent, ActionListener, KeyAdapter, KeyEvent, MouseAdapter, MouseEvent}
import java.awt.image.BufferedImage
import java.io.{File, PrintWriter}
import javax.swing.{JFrame, JPanel, SwingUtilities, Timer, WindowConstants}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

// ================================================================
// NOVA: TIMEFALL - THE LOST DIMENSION (SMOOTH NO-OUTLINE 3D)
// Original Scala + Java Swing 3D-style exploration platform game with smooth filled surfaces and no polygon edge outlines.
// No external libraries or copied game assets are required.
// ================================================================
object NovaTimefall {
  case class V3(x: Double, y: Double, z: Double) {
    def +(b: V3): V3 = V3(x + b.x, y + b.y, z + b.z)
    def -(b: V3): V3 = V3(x - b.x, y - b.y, z - b.z)
    def *(k: Double): V3 = V3(x * k, y * k, z * k)
  }
  case class Tri(a: V3, b: V3, c: V3, color: Color)
  case class CamV(x: Double, y: Double, z: Double)
  case class DrawFace(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int, depth: Double, color: Color)
  final class Platform(var x: Double, val y: Double, val z: Double,
                       val w: Double, val d: Double, val moving: Boolean = false,
                       val phase: Double = 0.0, val worldPhase: Int = -1) {
    var previousX: Double = x
  }
  final class Gem(val x: Double, val y: Double, val z: Double, val kind: Int) {
    var collected = false
  }
  final class Beacon(val x: Double, val y: Double, val z: Double, val label: String) {
    var active = false
  }
  final class TemporalGate(val x: Double, val y: Double, val z: Double,
                           val requiredPhase: Int, val label: String) {
    var active = false
  }
  final class Cloud(val x: Double, val y: Double, val z: Double, val scale: Double, val phase: Double)

  val VIEW_W = 1120
  val VIEW_H = 720
  val NEAR = 0.35
  val FOCAL = 760.0
  val FLOOR_COLOR = new Color(57, 100, 78)
  val SKY_COLOR = new Color(11, 21, 49)
  val PAST_SKY_PAINT = new GradientPaint(0f,0f,new Color(41,18,48),0f,720f,new Color(178,102,77))
  val FUTURE_SKY_PAINT = new GradientPaint(0f,0f,new Color(5,17,47),0f,720f,new Color(19,106,132))
  val PAST_GEM_COLORS = Array(new Color(255,179,92),new Color(248,121,156),new Color(255,215,125),new Color(197,155,255),new Color(255,231,157))
  val FUTURE_GEM_COLORS = Array(new Color(92,244,224),new Color(250,113,199),new Color(140,157,255),new Color(255,208,91),new Color(107,255,160))
  val LIGHT_DIR = normalize(V3(-0.45, 0.82, -0.38))

  val platforms = ArrayBuffer[Platform]()
  val staticTriangles = ArrayBuffer[Tri]()
  val gems = ArrayBuffer[Gem]()
  val beacons = ArrayBuffer[Beacon]()
  val temporalGates = ArrayBuffer[TemporalGate]()
  val clouds = ArrayBuffer[Cloud]()
  val keys = mutable.HashSet[Int]()
  // Reused render buffers avoid allocating a new world/face list every frame.
  val frameTriangles = ArrayBuffer[Tri]()
  val renderFaces = ArrayBuffer[DrawFace]()
  val clipScratch = ArrayBuffer[CamV]()
  var pastPlatformMesh = ArrayBuffer[Tri]()
  var futurePlatformMesh = ArrayBuffer[Tri]()

  var frame: JFrame = null
  var gamePanel: GamePanel = null
  var gameTimer: Timer = null
  var started = false
  var paused = false
  var won = false
  var glowOn = true
  var timePhase = 0                 // 0 = PAST, 1 = FUTURE
  var timeShiftCooldown = 0.0
  var phaseFlash = 0.0
  var gliding = false
  var timeGateCount = 0
  var mapOn = true
  var helpOn = false
  var message = "RESTORE THE TIMELINE"
  var messageTime = 5.0
  var time = 0.0
  var animTime = 0.0
  var px = 0.0
  var py = 0.0
  var pz = 0.0
  var vy = 0.0
  var grounded = true
  var yaw = 0.0
  var pitch = -0.22
  var jumpQueued = false
  var dashTime = 0.0
  var dashCooldown = 0.0
  var dashDX = 0.0
  var dashDZ = 1.0
  var stamina = 100.0
  var score = 0
  var gemCount = 0
  var beaconCount = 0
  var checkpointX = 0.0
  var checkpointY = 0.0
  var checkpointZ = 0.0
  var checkpointIndex = 0
  var lastMouseX = -1
  var lastMouseY = -1
  var mouseDown = false
  var playerWalk = 0.0
  var highScore = 0
  var lastSaveFile = new File(System.getProperty("user.home"), ".nova_timefall_highscore")

  def clamp(v: Double, lo: Double, hi: Double): Double = math.max(lo, math.min(hi, v))
  def dot(a: V3, b: V3): Double = a.x * b.x + a.y * b.y + a.z * b.z
  def cross(a: V3, b: V3): V3 = V3(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x)
  def length(v: V3): Double = math.sqrt(dot(v, v))
  def normalize(v: V3): V3 = { val n = length(v); if (n < 0.000001) V3(0,1,0) else V3(v.x/n,v.y/n,v.z/n) }
  def mixColor(a: Color, b: Color, t0: Double): Color = {
    val t = clamp(t0, 0.0, 1.0)
    new Color((a.getRed*(1-t)+b.getRed*t).toInt, (a.getGreen*(1-t)+b.getGreen*t).toInt,
      (a.getBlue*(1-t)+b.getBlue*t).toInt)
  }
  def lit(c: Color, amount: Double): Color = {
    val f = clamp(amount, 0.18, 1.45)
    new Color(clamp(c.getRed*f,0,255).toInt, clamp(c.getGreen*f,0,255).toInt,
      clamp(c.getBlue*f,0,255).toInt, c.getAlpha)
  }
  def distXZ(x1: Double, z1: Double, x2: Double, z2: Double): Double = {
    val dx=x1-x2; val dz=z1-z2; math.sqrt(dx*dx+dz*dz)
  }

  def emit(out: ArrayBuffer[Tri], a: V3, b: V3, c: V3, base: Color): Unit = {
    val n = normalize(cross(b-a,c-a))
    val diffuse = math.abs(dot(n, LIGHT_DIR))
    val shade = 0.42 + 0.66*diffuse
    out += Tri(a,b,c,lit(base,shade))
  }

  def addBox(out: ArrayBuffer[Tri], cx: Double, cy: Double, cz: Double,
             sx: Double, sy: Double, sz: Double, color: Color): Unit = {
    val x0=cx-sx/2; val x1=cx+sx/2
    val y0=cy-sy/2; val y1=cy+sy/2
    val z0=cz-sz/2; val z1=cz+sz/2
    val v=Array(V3(x0,y0,z0),V3(x1,y0,z0),V3(x1,y1,z0),V3(x0,y1,z0),
      V3(x0,y0,z1),V3(x1,y0,z1),V3(x1,y1,z1),V3(x0,y1,z1))
    val faces=Array(Array(0,3,2,1),Array(4,5,6,7),Array(0,4,7,3),
      Array(1,2,6,5),Array(3,7,6,2),Array(0,1,5,4))
    val shades=Array(0.82,1.12,0.72,0.88,1.22,0.56)
    var i=0
    while(i<faces.length) {
      val f=faces(i); val col=lit(color,shades(i))
      out += Tri(v(f(0)),v(f(1)),v(f(2)),col)
      out += Tri(v(f(0)),v(f(2)),v(f(3)),col)
      i+=1
    }
  }

  def addEllipsoid(out: ArrayBuffer[Tri], center: V3, rx: Double, ry: Double, rz: Double,
                   color: Color, lat: Int = 13, lon: Int = 20): Unit = {
    // Capped mesh density keeps animation responsive on Swing's software renderer.
    val latN = math.max(4, math.min(lat, 6))
    val lonN = math.max(6, math.min(lon, 8))
    def point(i: Int, j: Int): V3 = {
      val p=math.Pi*i.toDouble/latN; val t=2.0*math.Pi*j.toDouble/lonN
      V3(center.x+rx*math.sin(p)*math.cos(t), center.y+ry*math.cos(p), center.z+rz*math.sin(p)*math.sin(t))
    }
    var i=0
    while(i<latN) { var j=0
      while(j<lonN) {
        val a=point(i,j); val b=point(i+1,j); val c=point(i+1,(j+1)%lonN); val d=point(i,(j+1)%lonN)
        emit(out,a,b,c,color); emit(out,a,c,d,color); j+=1
      }; i+=1
    }
  }

  def addCylinder(out: ArrayBuffer[Tri], a: V3, b: V3, radiusA: Double, radiusB: Double,
                  color: Color, segments: Int = 10): Unit = {
    val sides = math.max(5, math.min(segments, 7))
    val axis=normalize(b-a)
    val helper=if(math.abs(axis.y)<0.88) V3(0,1,0) else V3(1,0,0)
    val u=normalize(cross(axis,helper)); val v=normalize(cross(axis,u))
    val ra=new Array[V3](sides); val rb=new Array[V3](sides)
    var i=0
    while(i<sides) {
      val t=2.0*math.Pi*i/sides
      ra(i)=a+u*(math.cos(t)*radiusA)+v*(math.sin(t)*radiusA)
      rb(i)=b+u*(math.cos(t)*radiusB)+v*(math.sin(t)*radiusB)
      i+=1
    }
    i=0
    while(i<sides) {
      val j=(i+1)%sides
      emit(out,ra(i),ra(j),rb(j),color); emit(out,ra(i),rb(j),rb(i),color)
      emit(out,a,ra(j),ra(i),color); emit(out,b,rb(i),rb(j),color)
      i+=1
    }
  }

  def addTorusXZ(out: ArrayBuffer[Tri], cx: Double, cy: Double, cz: Double,
                 major: Double, tube: Double, color: Color, sides: Int = 28, rings: Int = 7): Unit = {
    val sideN = math.max(10, math.min(sides, 16))
    val ringN = math.max(4, math.min(rings, 4))
    def p(i: Int,j: Int): V3 = {
      val t=2.0*math.Pi*i/sideN; val u=2.0*math.Pi*j/ringN
      V3(cx+(major+tube*math.cos(u))*math.cos(t),cy+tube*math.sin(u),cz+(major+tube*math.cos(u))*math.sin(t))
    }
    var i=0
    while(i<sideN) { var j=0
      while(j<ringN) {
        val a=p(i,j); val b=p((i+1)%sideN,j); val c=p((i+1)%sideN,(j+1)%ringN); val d=p(i,(j+1)%ringN)
        emit(out,a,b,c,color); emit(out,a,c,d,color); j+=1
      }; i+=1
    }
  }

  def addCrystal(out: ArrayBuffer[Tri], x: Double, y: Double, z: Double, spin: Double, scale: Double, color: Color): Unit = {
    val sides=6
    val top=V3(x,y+scale*1.05,z)
    val bottom=V3(x,y-scale*1.05,z)
    val ring=new Array[V3](sides)
    var i=0
    while(i<sides) { val a=2.0*math.Pi*i/sides+spin
      ring(i)=V3(x+math.cos(a)*scale*0.62,y+math.sin(i*1.7)*scale*0.07,z+math.sin(a)*scale*0.62); i+=1 }
    i=0
    while(i<sides) { val j=(i+1)%sides
      emit(out,top,ring(i),ring(j),mixColor(color,Color.WHITE,0.30))
      emit(out,bottom,ring(j),ring(i),mixColor(color,new Color(16,35,75),0.34)); i+=1
    }
    addTorusXZ(out,x,y-scale*1.28,z,scale*0.72,0.018*scale/0.7,new Color(79,246,223),12,4)
  }

  def addFlower(out: ArrayBuffer[Tri], x: Double, y: Double, z: Double, phase: Double): Unit = {
    val petal= if((phase.toInt&1)==0) new Color(255,105,190) else new Color(86,235,221)
    addCylinder(out,V3(x,y,z),V3(x,y+0.38,z),0.032,0.023,new Color(63,164,104),6)
    addEllipsoid(out,V3(x,y+0.40,z),0.09,0.065,0.09,new Color(250,207,79),4,6)
    var i=0
    while(i<5) { val a=phase+i*2.0*math.Pi/5.0
      addEllipsoid(out,V3(x+math.cos(a)*0.14,y+0.43,z+math.sin(a)*0.14),0.105,0.05,0.078,petal,4,6); i+=1 }
  }

  def addTree(out: ArrayBuffer[Tri], x: Double, y: Double, z: Double, size: Double): Unit = {
    addCylinder(out,V3(x,y,z),V3(x,y+size*1.1,z),0.15*size,0.10*size,new Color(91,65,48),9)
    addEllipsoid(out,V3(x,y+size*1.33,z),size*0.52,size*0.50,size*0.50,new Color(36,157,117),8,12)
    addEllipsoid(out,V3(x-size*0.24,y+size*1.52,z+size*0.08),size*0.34,size*0.35,size*0.32,new Color(53,193,142),8,12)
    addEllipsoid(out,V3(x+size*0.24,y+size*1.48,z-size*0.05),size*0.32,size*0.34,size*0.31,new Color(48,174,134),8,12)
  }

  def addPlayer(out: ArrayBuffer[Tri]): Unit = {
    val bob=if(grounded) math.sin(playerWalk)*0.045 else 0.0
    val swing=if(grounded) math.sin(playerWalk)*0.24 else 0.04
    val bodyY=py+0.98+bob
    val suit=new Color(34,96,166)
    addEllipsoid(out,V3(px,bodyY,pz),0.34,0.48,0.25,suit,12,18)
    addEllipsoid(out,V3(px,py+1.68+bob,pz+0.025),0.25,0.27,0.24,new Color(236,185,145),12,18)
    addEllipsoid(out,V3(px,py+1.75+bob,pz-0.015),0.25,0.115,0.24,new Color(32,44,66),10,16)
    addEllipsoid(out,V3(px,py+1.70+bob,pz+0.235),0.145,0.055,0.025,new Color(72,244,235),9,16)
    addBox(out,px,py+1.06+bob,pz-0.255,0.28,0.39,0.10,new Color(25,53,77))
    val leftHip=V3(px-0.13,py+0.67+bob,pz); val leftFoot=V3(px-0.15+math.sin(swing)*0.13,py+0.12,pz+math.cos(swing)*0.15)
    val rightHip=V3(px+0.13,py+0.67+bob,pz); val rightFoot=V3(px+0.15-math.sin(swing)*0.13,py+0.12,pz-math.cos(swing)*0.15)
    addCylinder(out,leftHip,leftFoot,0.105,0.075,new Color(31,62,111),8)
    addCylinder(out,rightHip,rightFoot,0.105,0.075,new Color(31,62,111),8)
    addEllipsoid(out,V3(leftFoot.x,py+0.09,leftFoot.z+0.06),0.13,0.07,0.19,new Color(21,28,41),7,10)
    addEllipsoid(out,V3(rightFoot.x,py+0.09,rightFoot.z+0.06),0.13,0.07,0.19,new Color(21,28,41),7,10)
    val lShoulder=V3(px-0.34,bodyY+0.22,pz); val lHand=V3(px-0.48,bodyY-0.18+swing,pz+0.03)
    val rShoulder=V3(px+0.34,bodyY+0.22,pz); val rHand=V3(px+0.48,bodyY-0.18-swing,pz+0.03)
    addCylinder(out,lShoulder,lHand,0.10,0.075,suit,8); addCylinder(out,rShoulder,rHand,0.10,0.075,suit,8)
    addEllipsoid(out,lHand,0.085,0.085,0.085,new Color(236,185,145),7,9)
    addEllipsoid(out,rHand,0.085,0.085,0.085,new Color(236,185,145),7,9)
  }

  def loadHighScore(): Unit = {
    try { if(lastSaveFile.exists()) highScore=scala.io.Source.fromFile(lastSaveFile).getLines().take(1).mkString.trim.toInt }
    catch { case _: Throwable => highScore=0 }
  }
  def saveHighScore(): Unit = {
    try { val w=new PrintWriter(lastSaveFile); try w.println(highScore) finally w.close() }
    catch { case _: Throwable => () }
  }

  def buildLevel(): Unit = {
    platforms.clear(); staticTriangles.clear(); gems.clear(); beacons.clear(); temporalGates.clear(); clouds.clear()
    pastPlatformMesh.clear(); futurePlatformMesh.clear()
    // Main route: safe launch isle, bridges, rising isles, a moving sky lift and portal isle.
    platforms += new Platform(0.0,0.0,0.0,10.0,10.0)
    platforms += new Platform(0.0,0.0,7.4,3.0,7.0)
    platforms += new Platform(0.6,1.6,15.0,8.5,8.0)
    platforms += new Platform(2.8,1.6,21.9,3.0,6.5)
    platforms += new Platform(6.0,3.2,29.0,9.0,9.0)
    platforms += new Platform(6.0,3.2,36.0,3.0,6.0)
    platforms += new Platform(2.0,3.2,41.0,3.0,3.0,true,0.6)
    platforms += new Platform(-2.2,4.8,46.7,3.0,7.0)
    platforms += new Platform(-2.2,4.8,53.0,9.5,9.0)
    platforms += new Platform(-2.2,4.8,60.0,3.0,5.0)
    platforms += new Platform(-2.2,6.4,67.0,11.0,10.0)
    // Time-locked stepping stones: the PAST and FUTURE reveal different routes.
    platforms += new Platform(-1.8,0.85,10.4,3.6,3.2,false,0.0,1)
    platforms += new Platform(4.4,2.45,22.8,3.5,3.1,false,0.0,0)
    platforms += new Platform(-5.1,4.95,44.5,3.3,3.2,false,0.0,1)
    platforms += new Platform(2.8,5.8,57.0,3.5,3.1,false,0.0,0)

    gems += new Gem(1.9,1.1,2.1,0)
    gems += new Gem(-1.5,2.7,14.5,1)
    gems += new Gem(8.3,4.3,28.5,2)
    gems += new Gem(-4.5,5.9,52.3,3)
    gems += new Gem(-2.2,7.5,67.0,4)
    beacons += new Beacon(2.6,1.6,14.6,"VERDANT BEACON")
    beacons += new Beacon(8.8,3.2,28.6,"AURORA BEACON")
    beacons += new Beacon(-5.2,4.8,53.0,"ZENITH BEACON")
    temporalGates += new TemporalGate(-1.9,1.6,15.7,0,"PAST MEMORY RIFT")
    temporalGates += new TemporalGate(8.3,3.2,30.7,1,"FUTURE MEMORY RIFT")
    temporalGates += new TemporalGate(-4.7,4.8,54.6,0,"ORIGIN MEMORY RIFT")
    clouds += new Cloud(-9,10,14,1.9,0.2); clouds += new Cloud(10,12,24,2.2,1.1)
    clouds += new Cloud(-8,14,46,2.5,2.2); clouds += new Cloud(8,13,60,2.0,3.1)

    // Build static decoration on the fixed islands.
    addTree(staticTriangles,-3.1,0.0,-2.7,1.05)
    addTree(staticTriangles,3.2,0.0,2.8,0.82)
    addTree(staticTriangles,-2.2,1.6,13.3,0.9)
    addTree(staticTriangles,3.2,1.6,16.8,0.72)
    addTree(staticTriangles,8.7,3.2,27.1,0.95)
    addTree(staticTriangles,3.1,3.2,31.0,0.78)
    addTree(staticTriangles,-5.5,4.8,50.5,0.94)
    addTree(staticTriangles,0.7,4.8,54.8,0.72)
    addTree(staticTriangles,1.8,6.4,64.3,0.95)
    // Ancient chrono pylons and broken timeline arches decorate the route.
    addCylinder(staticTriangles,V3(-4.0,0.0,1.4),V3(-4.0,2.5,1.4),0.12,0.08,new Color(131,103,82),10)
    addTorusXZ(staticTriangles,-4.0,2.42,1.4,0.56,0.045,new Color(255,190,113),24,6)
    addCylinder(staticTriangles, V3(4.2,1.6,16.7), V3(4.2,3.8,16.7), 0.10,0.08,new Color(89,124,151),10)
    addTorusXZ(staticTriangles,4.2,3.72,16.7,0.50,0.04,new Color(90,235,236),24,6)
    addCylinder(staticTriangles,V3(-6.0,4.8,51.0),V3(-6.0,7.4,51.0),0.12,0.08,new Color(87,107,145),10)
    addTorusXZ(staticTriangles,-6.0,7.32,51.0,0.62,0.05,new Color(159,135,255),28,6)
    val flowerSpots=Array((2.8,0.0,1.0),( -3.2,0.0,2.3),(1.5,0.0,-3.1),(-1.5,1.6,12.6),(2.2,1.6,17.1),
      (-2.0,1.6,15.8),(4.2,3.2,27.0),(7.5,3.2,32.1),(4.4,3.2,30.2),(-4.5,4.8,51.7),(-1.0,4.8,55.8),
      (-4.2,4.8,49.6),(-4.5,6.4,65.8),(1.0,6.4,68.6))
    var fi=0
    while(fi<flowerSpots.length) { val f=flowerSpots(fi); addFlower(staticTriangles,f._1,f._2,f._3,fi*0.71); fi+=1 }
    // Small floating rocks beneath the islands.
    platforms.foreach { p =>
      addBox(staticTriangles,p.x-0.7,p.y-1.15,p.z+0.2,1.1,1.4,1.2,new Color(57,67,91))
      addBox(staticTriangles,p.x+0.8,p.y-0.85,p.z-0.6,0.8,1.0,0.9,new Color(63,71,94))
    }
    // Prebuild fixed platforms for both eras once; only the moving lift is rebuilt per frame.
    buildPlatformGeometry(pastPlatformMesh, 0, false)
    buildPlatformGeometry(futurePlatformMesh, 1, false)
  }

  def resetGame(): Unit = {
    buildLevel(); px=0.0; py=0.0; pz = -2.7; vy=0.0; grounded=true
    yaw=0.0; pitch = -0.22; started=false; paused=false; won=false; glowOn=true; mapOn=true; helpOn=false
    message="RESTORE THE TIMELINE"; messageTime=5.0; time=0.0; animTime=0.0; jumpQueued=false
    dashTime=0.0; dashCooldown=0.0; stamina=100.0; score=0; gemCount=0; beaconCount=0
    timePhase=0; timeShiftCooldown=0.0; phaseFlash=0.0; gliding=false; timeGateCount=0
    checkpointX=0.0; checkpointY=0.0; checkpointZ = -2.7; checkpointIndex=0; keys.clear(); playerWalk=0.0
  }

  def platformAt(x: Double,z: Double): Option[Platform] = {
    platforms.filter(p => (p.worldPhase < 0 || p.worldPhase == timePhase) &&
      math.abs(x-p.x) <= p.w/2.0-0.12 && math.abs(z-p.z) <= p.d/2.0-0.12)
      .sortBy(p => -p.y).headOption
  }

  def updatePlatforms(dt: Double): Unit = {
    platforms.foreach { p =>
      p.previousX=p.x
      if(p.moving) p.x=2.0+math.sin(time*0.72+p.phase)*3.7
    }
  }

  def startGame(): Unit = { started=true; paused=false; say("TIMEFALL ONLINE. COLLECT MEMORY SHARDS AND RESTORE THE TIMELINE.",4.0) }
  def say(s: String, seconds: Double = 2.8): Unit = { message=s; messageTime=seconds }

  def tryJump(): Unit = { if(started && !paused && grounded && !won) { vy=8.4; grounded=false; jumpQueued=false; say("SKY JUMP!",0.7) } }
  def tryDash(): Unit = {
    if(started && !paused && !won && dashCooldown<=0.0) {
      val fx=math.sin(yaw); val fz=math.cos(yaw)
      dashDX=fx; dashDZ=fz; dashTime=0.20; dashCooldown=1.35
      say("CYBER DASH",0.8)
    }
  }

  def shiftTime(): Unit = {
    if(!started || paused || won || timeShiftCooldown > 0.0) return
    timePhase = 1 - timePhase
    timeShiftCooldown = 1.15
    phaseFlash = 0.58
    say(if(timePhase == 0) "TIME SHIFT: PAST ERA" else "TIME SHIFT: FUTURE ERA", 1.6)
    try { Toolkit.getDefaultToolkit.beep() } catch { case _: Throwable => () }
  }

  def interact(): Unit = {
    if(!started || paused || won) return
    val nearGate = temporalGates.filter(g => !g.active && distXZ(px,pz,g.x,g.z)<2.0 && math.abs(py-g.y)<2.1)
      .sortBy(g => distXZ(px,pz,g.x,g.z)).headOption
    nearGate match {
      case Some(g) if g.requiredPhase == timePhase =>
        g.active=true; timeGateCount+=1; score+=350
        say(g.label + " RESTORED! MEMORY " + timeGateCount + " / 3", 3.0)
        return
      case Some(g) =>
        say(g.label + " REQUIRES THE " + (if(g.requiredPhase==0) "PAST" else "FUTURE") + " ERA. PRESS T TO SHIFT.", 3.0)
        return
      case None => ()
    }
    val nearBeacon=beacons.filter(b => distXZ(px,pz,b.x,b.z)<2.25).sortBy(b=>distXZ(px,pz,b.x,b.z)).headOption
    nearBeacon match {
      case Some(b) if !b.active =>
        b.active=true; beaconCount+=1; score+=250; say(b.label+" STABILIZED!",3.0)
      case Some(b) => say(b.label+" IS ALREADY ONLINE.")
      case None =>
        val nearPortal=distXZ(px,pz,-2.2,67.0)<3.2 && math.abs(py-6.4)<1.4
        if(nearPortal) {
          if(gemCount>=5 && beaconCount>=3 && timeGateCount>=3) { won=true; score+=1500; if(score>highScore){highScore=score;saveHighScore()}; say("TIMELINE RESTORED! THE LOST DIMENSION IS SAVED.",30.0) }
          else say("PORTAL LOCKED: 5 SEEDS + 3 BEACONS + 3 MEMORY RIFTS REQUIRED.",4.0)
        } else say("MOVE CLOSER TO A BEACON OR THE SKY PORTAL.")
    }
  }

  def checkpointUpdate(): Unit = {
    if(checkpointIndex<1 && pz>12.0 && py>1.0) { checkpointX=0.6; checkpointY=1.6; checkpointZ=14.0; checkpointIndex=1; say("CHECKPOINT UNLOCKED: VERDANT ISLE",2.5) }
    if(checkpointIndex<2 && pz>27.0 && py>2.5) { checkpointX=6.0; checkpointY=3.2; checkpointZ=28.0; checkpointIndex=2; say("CHECKPOINT UNLOCKED: AURORA ISLE",2.5) }
    if(checkpointIndex<3 && pz>51.0 && py>4.0) { checkpointX = -2.2; checkpointY=4.8; checkpointZ=52.0; checkpointIndex=3; say("CHECKPOINT UNLOCKED: ZENITH ISLE",2.5) }
  }

  def updatePhysics(dt: Double): Unit = {
    // Carry the player along the moving sky lift while standing on it.
    if(grounded) platformAt(px,pz).filter(_.moving).foreach(p => px += p.x-p.previousX)
    var forward=0.0; var side=0.0
    if(keys.contains(KeyEvent.VK_W) || keys.contains(KeyEvent.VK_UP)) forward+=1.0
    if(keys.contains(KeyEvent.VK_S) || keys.contains(KeyEvent.VK_DOWN)) forward-=1.0
    if(keys.contains(KeyEvent.VK_D) || keys.contains(KeyEvent.VK_RIGHT)) side+=1.0
    if(keys.contains(KeyEvent.VK_A) || keys.contains(KeyEvent.VK_LEFT)) side-=1.0
    val moving=math.sqrt(forward*forward+side*side)
    if(moving>0.0 && !won) {
      forward/=moving; side/=moving
      val sprint=keys.contains(KeyEvent.VK_SHIFT) && stamina>1.0
      val speed=if(sprint) 7.2 else 4.7
      if(sprint) stamina=math.max(0.0,stamina-25.0*dt) else stamina=math.min(100.0,stamina+17.0*dt)
      var dx=(math.sin(yaw)*forward+math.cos(yaw)*side)*speed*dt
      var dz=(math.cos(yaw)*forward-math.sin(yaw)*side)*speed*dt
      if(dashTime>0.0) { dx+=dashDX*12.0*dt; dz+=dashDZ*12.0*dt }
      val nx=px+dx
      if(platformAt(nx,pz).isDefined || !grounded) px=nx
      val nz=pz+dz
      if(platformAt(px,nz).isDefined || !grounded) pz=nz
      playerWalk+=dt*12.0
    } else stamina=math.min(100.0,stamina+15.0*dt)

    val oldY=py
    if(grounded) {
      platformAt(px,pz) match {
        case Some(p) => py=p.y
        case None => grounded=false
      }
    }
    if(!grounded) {
      gliding = keys.contains(KeyEvent.VK_G)
      vy-= (if(gliding) 5.2 else 19.0)*dt
      if(gliding && vy < -2.5) vy = -2.5
      py+=vy*dt
      if(vy<=0.0) {
        platformAt(px,pz) match {
          case Some(p) if oldY>=p.y-0.16 && py<=p.y+0.12 => py=p.y; vy=0.0; grounded=true
          case _ => ()
        }
      }
    }
    if(py < -9.0) {
      px=checkpointX; py=checkpointY; pz=checkpointZ; vy=0.0; grounded=true; dashTime=0.0
      say("YOU FELL THROUGH THE CLOUDS. CHECKPOINT RESTORED.",3.0)
    }
    if(gemCount<5) {
      gems.foreach { gem => if(!gem.collected && distXZ(px,pz,gem.x,gem.z)<1.25 && math.abs(py-gem.y)<2.0) {
        gem.collected=true; gemCount+=1; score+=100; say("AETHER SEED COLLECTED  "+gemCount+" / 5",2.0)
      }}
    }
    checkpointUpdate()
    if(dashTime>0.0) dashTime=math.max(0.0,dashTime-dt)
    if(dashCooldown>0.0) dashCooldown=math.max(0.0,dashCooldown-dt)
  }

  def updateGame(dt0: Double): Unit = {
    val dt=clamp(dt0,0.0,0.05)
    animTime+=dt
    if(!started || paused || won) return
    time+=dt
    if(messageTime>0.0) messageTime=math.max(0.0,messageTime-dt)
    if(timeShiftCooldown>0.0) timeShiftCooldown=math.max(0.0,timeShiftCooldown-dt)
    if(phaseFlash>0.0) phaseFlash=math.max(0.0,phaseFlash-dt)
    updatePlatforms(dt)
    if(jumpQueued) tryJump()
    updatePhysics(dt)
  }

  var camX=0.0; var camY=0.0; var camZ=0.0
  var camCosYaw=1.0; var camSinYaw=0.0; var camCosPitch=1.0; var camSinPitch=0.0
  def prepareCamera(): Unit = {
    camX=px-math.sin(yaw)*8.6; camY=py+4.55; camZ=pz-math.cos(yaw)*8.6
    camCosYaw=math.cos(yaw); camSinYaw=math.sin(yaw)
    camCosPitch=math.cos(pitch); camSinPitch=math.sin(pitch)
  }
  def camera(v: V3): CamV = {
    val dx=v.x-camX; val dy=v.y-camY; val dz=v.z-camZ
    val cx=dx*camCosYaw-dz*camSinYaw
    val forward=dx*camSinYaw+dz*camCosYaw
    CamV(cx,dy*camCosPitch-forward*camSinPitch,dy*camSinPitch+forward*camCosPitch)
  }

  def clipEdge(p: CamV, q: CamV, out: ArrayBuffer[CamV]): Unit = {
    val ip=p.z>=NEAR; val iq=q.z>=NEAR
    if(ip && iq) out+=q
    else if(ip && !iq) { val t=(NEAR-p.z)/(q.z-p.z); out+=CamV(p.x+(q.x-p.x)*t,p.y+(q.y-p.y)*t,NEAR) }
    else if(!ip && iq) { val t=(NEAR-p.z)/(q.z-p.z); out+=CamV(p.x+(q.x-p.x)*t,p.y+(q.y-p.y)*t,NEAR); out+=q }
  }
  def clipNearInto(a: CamV, b: CamV, c: CamV, out: ArrayBuffer[CamV]): Unit = {
    out.clear()
    clipEdge(a,b,out); clipEdge(b,c,out); clipEdge(c,a,out)
  }

  def project(v: CamV,w: Int,h: Int): (Int,Int) = {
    val sx=w/2.0+v.x*FOCAL/v.z
    val sy=h/2.0-v.y*FOCAL/v.z
    (sx.toInt,sy.toInt)
  }

  def buildPlatformGeometry(out: ArrayBuffer[Tri], phase: Int, includeMoving: Boolean): Unit = {
    platforms.filter(p => (p.worldPhase < 0 || p.worldPhase == phase) && p.moving == includeMoving).foreach { p =>
      val top=p.y
      val rock=if(phase==0) new Color(73,72,105) else new Color(42,70,100)
      val grass=if(phase==0) new Color(116,111,83) else new Color(42,139,137)
      val turf=if(phase==0) new Color(179,151,91) else new Color(84,202,174)
      addBox(out,p.x,top-0.34,p.z,p.w,0.68,p.d,rock)
      addBox(out,p.x,top-0.015,p.z,p.w-0.12,0.10,p.d-0.12,grass)
      addBox(out,p.x,top+0.045,p.z,p.w-0.32,0.035,p.d-0.32,turf)
    }
  }


  def buildDynamic(out: ArrayBuffer[Tri]): Unit = {
    // The static island meshes are cached; only the moving platform needs fresh geometry.
    buildPlatformGeometry(out, timePhase, true)
    gems.foreach { g => if(!g.collected && distXZ(px,pz,g.x,g.z)<34.0) {
      val bob=math.sin(animTime*2.5+g.kind)*0.19
      val col=if(timePhase==0) PAST_GEM_COLORS(g.kind) else FUTURE_GEM_COLORS(g.kind)
      addCrystal(out,g.x,g.y+bob,g.z,animTime*1.45+g.kind,0.72,col)
    }}
    temporalGates.foreach { gate => if(distXZ(px,pz,gate.x,gate.z)<30.0) {
      val pulse=0.5+0.5*math.sin(animTime*3.0+gate.requiredPhase)
      val base=if(gate.active) new Color(91,255,172) else if(gate.requiredPhase==timePhase) new Color(255,200,103) else new Color(119,132,210)
      val col=mixColor(base,Color.WHITE,pulse*0.22)
      addTorusXZ(out,gate.x,gate.y+0.65,gate.z,0.66+0.06*pulse,0.045,col,16,4)
      addTorusXZ(out,gate.x,gate.y+1.18,gate.z,0.43,0.03,col,14,4)
      addEllipsoid(out,V3(gate.x,gate.y+0.70+math.sin(animTime*2.0)*0.11,gate.z),0.28,0.42,0.12,new Color(col.getRed,col.getGreen,col.getBlue,115),6,8)
    }}
    beacons.foreach { b => if(distXZ(px,pz,b.x,b.z)<30.0) {
      val col=if(b.active) new Color(87,255,160) else if(timePhase==0) new Color(255,187,108) else new Color(83,219,255)
      addCylinder(out,V3(b.x,b.y,b.z),V3(b.x,b.y+1.1,b.z),0.21,0.14,new Color(50,83,112),8)
      addEllipsoid(out,V3(b.x,b.y+1.3+math.sin(animTime*2.0)*0.12,b.z),0.25,0.31,0.25,col,6,8)
      addTorusXZ(out,b.x,b.y+0.72,b.z,0.48,0.03,col,14,4)
      if(glowOn && !b.active) addTorusXZ(out,b.x,b.y+1.38,b.z,0.62,0.018,new Color(141,247,255),14,4)
    }}
    // Clouds are drawn as inexpensive sky layers, not rebuilt as 3D meshes every frame.
    // Portal geometry is added only near the final island.
    if(distXZ(px,pz,-2.2,67.0)<34.0) {
      addBox(out,-4.2,7.55,67.0,0.35,2.5,0.45,new Color(49,75,105))
      addBox(out,-0.2,7.55,67.0,0.35,2.5,0.45,new Color(49,75,105))
      addBox(out,-2.2,8.78,67.0,4.2,0.35,0.45,new Color(62,107,138))
      val portalCol=if(gemCount>=5 && beaconCount>=3 && timeGateCount>=3) new Color(83,255,201) else new Color(112,129,177)
      addTorusXZ(out,-2.2,7.55,67.05,1.15,0.055,portalCol,16,4)
      addEllipsoid(out,V3(-2.2,7.55,67.12),0.82,1.05,0.08,new Color(40,94,132,170),6,8)
    }
    addPlayer(out)
  }

  def drawBackground(g: Graphics2D,w: Int,h: Int): Unit = {
    if(timePhase==0) g.setPaint(PAST_SKY_PAINT) else g.setPaint(FUTURE_SKY_PAINT)
    g.fillRect(0,0,w,h)
    g.setColor(new Color(75,122,167,36)); g.fillOval(-w/4,h/3,w,h/3)
    g.setColor(new Color(128,180,202,20)); g.fillOval(w/3,h/4,w,h/3)
    // Low-cost static stars; avoiding a new Color and trigonometry per star per frame.
    var i=0
    while(i<38) {
      val x=((i*173+31)%w); val y=((i*97+19)%(h/2))
      if(timePhase==0) g.setColor(new Color(255,215,169,95)) else g.setColor(new Color(160,230,255,105))
      val r=2+(i%2); g.fillOval(x,y,r,r); i+=1
    }
  }

  def render3D(g: Graphics2D,w: Int,h: Int): Unit = {
    drawBackground(g,w,h)
    frameTriangles.clear()
    frameTriangles ++= staticTriangles
    if(timePhase==0) frameTriangles ++= pastPlatformMesh else frameTriangles ++= futurePlatformMesh
    buildDynamic(frameTriangles)
    prepareCamera()
    renderFaces.clear()
    frameTriangles.foreach { t =>
      val wx=(t.a.x+t.b.x+t.c.x)/3.0
      val wz=(t.a.z+t.b.z+t.c.z)/3.0
      val dx=px-wx; val dz=pz-wz
      // Squared-distance culling avoids a square root for every triangle.
      if(dx*dx+dz*dz<60.0*60.0) {
        val ca=camera(t.a); val cb=camera(t.b); val cc=camera(t.c)
        clipNearInto(ca,cb,cc,clipScratch)
        if(clipScratch.length>=3) {
          var i=1
          while(i<clipScratch.length-1) {
            val a=project(clipScratch(0),w,h); val b=project(clipScratch(i),w,h); val c=project(clipScratch(i+1),w,h)
            val depth=(clipScratch(0).z+clipScratch(i).z+clipScratch(i+1).z)/3.0
            if(depth<105.0 && a._1 > -300 && a._1 < w + 300 && a._2 > -300 && a._2 < h + 300) {
              renderFaces += DrawFace(a._1,a._2,b._1,b._2,c._1,c._2,depth,t.color)
            }
            i+=1
          }
        }
      }
    }
    val ordered=renderFaces.sortBy(f => -f.depth)
    val xs=new Array[Int](3); val ys=new Array[Int](3)
    ordered.foreach { f =>
      // Use the pre-lit face colour directly; per-face fog colours created heavy GC pressure.
      g.setColor(f.color)
      xs(0)=f.x1; xs(1)=f.x2; xs(2)=f.x3
      ys(0)=f.y1; ys(1)=f.y2; ys(2)=f.y3
      g.fillPolygon(xs,ys,3)
    }
    drawHUD(g,w,h)
    if(phaseFlash > 0.0) {
      val alpha=clamp(phaseFlash/0.58*85.0,0.0,85.0).toInt
      val flashColor=if(timePhase==0) new Color(255,165,93,alpha) else new Color(82,230,255,alpha)
      g.setColor(flashColor); g.fillRect(0,0,w,h)
    }
  }

  def rounded(g: Graphics2D,x: Int,y: Int,w: Int,h: Int,c: Color,r: Int = 16): Unit = {
    g.setColor(c); g.fillRoundRect(x,y,w,h,r,r)
  }
  def drawBar(g: Graphics2D,x: Int,y: Int,w: Int,h: Int,value: Double,c: Color): Unit = {
    rounded(g,x,y,w,h,new Color(15,27,43,215),h)
    rounded(g,x,y,math.max(0,(w*clamp(value,0.0,1.0)).toInt),h,c,h)
  }

  def drawHUD(g: Graphics2D,w: Int,h: Int): Unit = {
    rounded(g,16,14,345,100,new Color(8,18,34,205),18)
    g.setColor(new Color(111,248,224)); g.setFont(new Font("Arial",Font.BOLD,17)); g.drawString("NOVA  /  TIMEFALL",30,39)
    g.setColor(new Color(221,238,248)); g.setFont(new Font("Arial",Font.PLAIN,12)); g.drawString("AETHER SEEDS  "+gemCount+" / 5",30,62)
    drawBar(g,30,70,145,8,gemCount/5.0,new Color(93,244,219))
    g.drawString("BEACONS  "+beaconCount+" / 3",194,62)
    drawBar(g,194,70,140,8,beaconCount/3.0,new Color(255,172,104))
    g.setColor(new Color(221,238,248)); g.setFont(new Font("Arial",Font.BOLD,11)); g.drawString("SCORE  "+score,30,99)

    rounded(g,w-204,14,188,75,new Color(8,18,34,195),16)
    g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.BOLD,12)); g.drawString("STAMINA",w-187,36)
    drawBar(g,w-187,45,150,9,stamina/100.0,new Color(122,206,255))
    g.setFont(new Font("Arial",Font.PLAIN,10)); g.setColor(new Color(187,209,228)); g.drawString("DASH  "+(if(dashCooldown<=0.0) "READY" else "RECHARGING"),w-187,73)
    rounded(g,w-204,96,188,34,new Color(8,18,34,205),13)
    g.setColor(if(timePhase==0) new Color(255,195,120) else new Color(99,238,255))
    g.setFont(new Font("Arial",Font.BOLD,12)); g.drawString(if(timePhase==0) "ERA: PAST" else "ERA: FUTURE",w-187,118)

    rounded(g,16,h-77,690,59,new Color(8,18,34,205),15)
    g.setColor(new Color(224,239,246)); g.setFont(new Font("Arial",Font.BOLD,11))
    g.drawString("WASD MOVE   SPACE JUMP   SHIFT SPRINT   Q DASH   G GLIDE   E INTERACT",29,h-53)
    g.setColor(new Color(150,186,208)); g.setFont(new Font("Arial",Font.PLAIN,10))
    g.drawString("T TIME SHIFT   M MAP   F GLOW   H HELP   ESC PAUSE   R RESTART   MOUSE DRAG CAMERA",29,h-33)

    if(mapOn) drawMiniMap(g,w)
    if(messageTime>0.0 && message.nonEmpty) {
      val mw=math.min(w-100,math.max(260,g.getFontMetrics(new Font("Arial",Font.BOLD,14)).stringWidth(message)+42))
      rounded(g,(w-mw)/2,104,mw,36,new Color(8,21,35,218),16)
      g.setColor(new Color(180,255,235)); g.setFont(new Font("Arial",Font.BOLD,14));
      g.drawString(message,(w-g.getFontMetrics.stringWidth(message))/2,127)
    }
    if(helpOn) {
      rounded(g,w/2-215,h/2-145,430,290,new Color(5,15,30,238),22)
      g.setColor(new Color(115,250,223)); g.setFont(new Font("Arial",Font.BOLD,22)); g.drawString("FIELD GUIDE",w/2-175,h/2-105)
      g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.PLAIN,14))
      val lines=Array("WASD / ARROWS  - Move across the broken timeline", "SPACE  - Jump across gaps", "SHIFT  - Sprint (uses stamina)", "Q  - Short cyber dash", "G  - Glide while airborne", "T  - Shift between PAST and FUTURE eras", "E  - Restore a memory rift / activate beacon", "Collect 5 shards, 3 beacons and 3 memory rifts.", "Reach the portal on Zenith Isle. Mouse drag: camera.")
      var yy=h/2-70; lines.foreach { s=>g.drawString(s,w/2-175,yy); yy+=27 }
      g.setColor(new Color(138,202,219)); g.drawString("Press H to close",w/2-175,h/2+125)
    }
  }

  def drawMiniMap(g: Graphics2D,w: Int): Unit = {
    val x=w-183; val y=105; val mw=167; val mh=190
    rounded(g,x,y,mw,mh,new Color(7,17,31,205),15)
    g.setColor(new Color(163,203,223)); g.setFont(new Font("Arial",Font.BOLD,10)); g.drawString("TIMEFALL MAP",x+12,y+17)
    def mapX(wx: Double): Int = x+mw/2+(wx*5.2).toInt
    def mapY(wz: Double): Int = y+28+(wz/70.0*145).toInt
    platforms.foreach { p =>
      g.setColor(if(p.moving) new Color(80,240,224) else new Color(79,149,133))
      val rw=math.max(4,(p.w*5.2).toInt); val rh=math.max(4,(p.d/70.0*145).toInt)
      g.fillRoundRect(mapX(p.x)-rw/2,mapY(p.z)-rh/2,rw,rh,5,5)
    }
    gems.foreach { gem => if(!gem.collected) { g.setColor(new Color(255,202,94)); g.fillOval(mapX(gem.x)-3,mapY(gem.z)-3,6,6) } }
    g.setColor(new Color(255,116,153)); beacons.foreach(b=>if(!b.active) g.fillOval(mapX(b.x)-3,mapY(b.z)-3,6,6))
    g.setColor(Color.WHITE); g.fillOval(mapX(px)-4,mapY(pz)-4,8,8)
  }

  def drawTitle(g: Graphics2D,w: Int,h: Int): Unit = {
    g.setPaint(new GradientPaint(0f,0f,new Color(6,15,39),w.toFloat,h.toFloat,new Color(18,74,91)))
    g.fillRect(0,0,w,h)
    var i=0
    while(i<44) {
      val a=i*2.399
      val x=w/2+math.cos(a)*(90+(i*23)%320)
      val y=h/2+math.sin(a)*(50+(i*17)%230)
      val r=2+(i%4)
      g.setColor(new Color(87,238,218,100+(i%5)*25)); g.fillOval(x.toInt,y.toInt,r,r); i+=1
    }
    g.setColor(new Color(82,247,222)); g.setFont(new Font("Arial",Font.BOLD,18)); g.drawString("TWO ERAS. ONE BROKEN WORLD.",w/2-145,100)
    g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.BOLD,48)); g.drawString("NOVA",w/2-82,174)
    g.setColor(new Color(255,191,112)); g.setFont(new Font("Arial",Font.BOLD,29)); g.drawString("TIMEFALL",w/2-90,216)
    g.setColor(new Color(197,225,236)); g.setFont(new Font("Arial",Font.PLAIN,16));
    g.drawString("THE LOST DIMENSION  /  3D TIME-SHIFT ADVENTURE",w/2-214,258)
    rounded(g,w/2-205,310,410,175,new Color(4,16,32,190),22)
    g.setColor(new Color(124,249,223)); g.setFont(new Font("Arial",Font.BOLD,20)); g.drawString("RESTORE THE TIMELINE",w/2-112,346)
    g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.PLAIN,14));
    g.drawString("Collect 5 Memory Shards",w/2-94,380)
    g.drawString("Activate 3 Chrono Beacons",w/2-106,405)
    g.drawString("Restore 3 Memory Rifts",w/2-91,430)
    g.drawString("Shift PAST / FUTURE with T to reveal paths",w/2-154,455)
    rounded(g,w/2-105,505,210,52,new Color(34,161,145),17)
    g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.BOLD,19)); g.drawString("PRESS ENTER",w/2-68,537)
    g.setColor(new Color(172,204,219)); g.setFont(new Font("Arial",Font.PLAIN,12)); g.drawString("WASD MOVE  |  SPACE JUMP  |  T TIME SHIFT  |  Q DASH  |  G GLIDE",w/2-216,h-55)
    if(highScore>0) { g.setFont(new Font("Arial",Font.BOLD,13)); g.setColor(new Color(255,218,131)); g.drawString("BEST SCORE  "+highScore,w/2-55,h-28) }
  }

  def drawPause(g: Graphics2D,w: Int,h: Int): Unit = {
    g.setColor(new Color(4,10,22,190)); g.fillRect(0,0,w,h)
    g.setColor(new Color(112,247,224)); g.setFont(new Font("Arial",Font.BOLD,38)); g.drawString("PAUSED",w/2-80,h/2-20)
    g.setColor(Color.WHITE); g.setFont(new Font("Arial",Font.PLAIN,16)); g.drawString("Press ESC to resume   |   R to restart",w/2-150,h/2+25)
  }

  class GamePanel extends JPanel {
    private var renderBuffer: BufferedImage = null
    private var bufferW = 0
    private var bufferH = 0
    setPreferredSize(new Dimension(VIEW_W,VIEW_H)); setFocusable(true); setBackground(Color.BLACK)
    override protected def paintComponent(g0: Graphics): Unit = {
      super.paintComponent(g0)
      val w=getWidth(); val h=getHeight()
      if(w<=0 || h<=0) return
      val rw=math.max(640,(w*0.78).toInt)
      val rh=math.max(410,(h*0.78).toInt)
      if(renderBuffer==null || rw!=bufferW || rh!=bufferH) {
        renderBuffer=new BufferedImage(rw,rh,BufferedImage.TYPE_INT_RGB)
        bufferW=rw; bufferH=rh
      }
      val rg=renderBuffer.createGraphics()
      rg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF)
      rg.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_SPEED)
      rg.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_COLOR_RENDER_SPEED)
      rg.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED)
      if(!started) drawTitle(rg,rw,rh)
      else {
        render3D(rg,rw,rh)
        if(paused) drawPause(rg,rw,rh)
        if(won) {
          rg.setColor(new Color(4,20,29,195)); rg.fillRect(0,0,rw,rh)
          rg.setColor(new Color(116,255,210)); rg.setFont(new Font("Arial",Font.BOLD,34)); rg.drawString("THE TIMELINE IS RESTORED!",rw/2-255,rh/2-20)
          rg.setColor(Color.WHITE); rg.setFont(new Font("Arial",Font.PLAIN,16)); rg.drawString("You reunited the Past and Future dimensions.",rw/2-165,rh/2+24)
          rg.drawString("Press R to explore again.",rw/2-88,rh/2+58)
        }
      }
      rg.dispose()
      val g=g0.create().asInstanceOf[Graphics2D]
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR)
      g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_SPEED)
      g.drawImage(renderBuffer,0,0,w,h,null)
      g.dispose()
    }
  }

  def installInput(): Unit = {
    gamePanel.addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent): Unit = {
        val k=e.getKeyCode
        if(k==KeyEvent.VK_ENTER && !started) startGame()
        else if(k==KeyEvent.VK_ESCAPE && started && !won) { paused = !paused; keys.clear() }
        else if(k==KeyEvent.VK_R) resetGame()
        else if(k==KeyEvent.VK_H) helpOn = !helpOn
        else if(k==KeyEvent.VK_M) mapOn = !mapOn
        else if(k==KeyEvent.VK_F) glowOn = !glowOn
        else if(k==KeyEvent.VK_E) interact()
        else if(k==KeyEvent.VK_SPACE) tryJump()
        else if(k==KeyEvent.VK_Q) tryDash()
        else if(k==KeyEvent.VK_T) shiftTime()
        if(!paused && !won) keys+=k
        gamePanel.repaint()
      }
      override def keyReleased(e: KeyEvent): Unit = { keys-=e.getKeyCode }
    })
    val mouse=new MouseAdapter {
      override def mousePressed(e: MouseEvent): Unit = { mouseDown=true; lastMouseX=e.getX; lastMouseY=e.getY; gamePanel.requestFocusInWindow() }
      override def mouseReleased(e: MouseEvent): Unit = { mouseDown=false; lastMouseX = -1; lastMouseY = -1 }
      override def mouseDragged(e: MouseEvent): Unit = {
        if(mouseDown && started && !paused && !won && lastMouseX>=0) {
          val dx=e.getX-lastMouseX; val dy=e.getY-lastMouseY
          yaw+=dx*0.006; pitch=clamp(pitch-dy*0.004,-0.78,0.18)
          lastMouseX=e.getX; lastMouseY=e.getY; gamePanel.repaint()
        }
      }
    }
    gamePanel.addMouseListener(mouse); gamePanel.addMouseMotionListener(mouse)
  }

  def show(): Unit = {
    loadHighScore(); resetGame()
    frame=new JFrame("NOVA: TIMEFALL - THE LOST DIMENSION (SMOOTH NO-OUTLINE 3D)")
    gamePanel=new GamePanel()
    frame.setContentPane(gamePanel); frame.pack(); frame.setMinimumSize(new Dimension(900,620)); frame.setLocationRelativeTo(null)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    installInput()
    gameTimer=new Timer(33,new ActionListener { private var previous=System.nanoTime()
      override def actionPerformed(e: ActionEvent): Unit = {
        val now=System.nanoTime(); val dt=(now-previous)/1000000000.0; previous=now
        updateGame(dt)
        if(!started || (!paused && !won)) gamePanel.repaint()
      }
    })
    frame.setVisible(true); gamePanel.requestFocusInWindow(); gameTimer.start()
  }

  def main(args: Array[String]): Unit = SwingUtilities.invokeLater(new Runnable {
    override def run(): Unit = show()
  })
}

NovaTimefall.main(Array[String]())