aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/phenax/extensions/CameraManager.kt
blob: ab2403cf1e49ff032f2c0c5069cbb668e66374ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package phenax.extensions

import org.openrndr.*
import org.openrndr.color.*
import org.openrndr.draw.*
import org.openrndr.math.Vector3
import phenax.utils.recordingEnabled

enum class ActionType {
  PAN,
  LIGHT_MOVE
}

class CameraManager : Extension {
  override var enabled: Boolean = true

  public var cameraPosition: Vector3 = Vector3(0.0, 1.0, 0.0)
  public var lightPosition: Vector3 = Vector3(1.0, 2.0, 1.0)

  var font: FontImageMap? = null
  var actionType: ActionType? = null
  var lastPos: Vector3? = null

  override fun setup(program: Program) {
    if (recordingEnabled) return

    font = program.loadFont("data/fonts/default.otf", 16.0)

    program.keyboard.keyDown.listen { if (it.key == KEY_ESCAPE) program.application.exit() }

    program.mouse.moved.listen {
      val dimens = Vector3(program.width.toDouble(), program.height.toDouble(), 1.0)
      val pos = (Vector3(it.position.x, -it.position.y, 0.0) - dimens / 2.0).div(dimens)
      if (actionType == ActionType.PAN) {
        lastPos?.let { lastPos -> cameraPosition -= (pos - lastPos) }
      } else if (actionType == ActionType.LIGHT_MOVE) {
        lastPos?.let { lastPos -> lightPosition += (pos - lastPos) }
      }
      actionType?.let { lastPos = pos }
    }

    program.mouse.buttonDown.listen {
      val isCtrl = KeyModifier.CTRL in it.modifiers
      actionType = if (isCtrl) ActionType.LIGHT_MOVE else ActionType.PAN
    }

    program.mouse.scrolled.listen {
      val isCtrl = KeyModifier.CTRL in it.modifiers
      if (isCtrl) {
        lightPosition += Vector3(0.0, 0.0, it.rotation.y * 0.1)
      } else {
        cameraPosition += Vector3(0.0, 0.0, it.rotation.y * 0.1)
      }
    }

    program.mouse.buttonUp.listen {
      actionType = null
      lastPos = null
    }
  }

  fun setUniforms(cs: ComputeShader) {
    cs.uniform("camera_position", cameraPosition)
    cs.uniform("primary_light_position", lightPosition)
  }

  override fun beforeDraw(drawer: Drawer, program: Program) {}

  override fun afterDraw(drawer: Drawer, program: Program) {
    if (recordingEnabled) return

    drawer.fontMap = font
    drawer.fill = ColorRGBa.WHITE
    drawer.text(
            "C: %.2f %.2f %.2f".format(cameraPosition.x, cameraPosition.y, cameraPosition.z),
            8.0,
            16.0
    )
    drawer.text(
            "L: %.2f %.2f %.2f".format(lightPosition.x, lightPosition.y, lightPosition.z),
            8.0,
            32.0
    )
  }
}