aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/phenax/utils/program.kt
blob: 6ff53799a82e4e4834b9df78201729a6f29179bc (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
package phenax.utils

import java.io.File
import kotlin.properties.ReadOnlyProperty
import org.openrndr.ApplicationBuilder
import org.openrndr.Program
import org.openrndr.draw.*
import org.openrndr.extra.filewatcher.watchingFile
import org.openrndr.extra.olive.oliveProgram as oliveProgramOriginal

fun Int.seconds(): Int = this * 1000

fun Int.minutes(): Int = this.seconds() * 60

fun recordDuration(millis: Int) {
  System.setProperty("phenax.record.frameCount", (60 * millis / 1000).toInt().toString())
}

fun recordDuration(): Int? = System.getProperty("phenax.record.frameCount")?.toIntOrNull()

val recordingEnabled: Boolean by lazy { System.getenv("RECORD") != null }

// fun classDir(): String =
//     "src/main/kotlin/${stackRootClassName(sanitize =
// true).split(".").dropLast(1).joinToString("/")}";

// fun localComputeShader(name: String): ComputeShader =
//         ComputeShader.fromCode(File("src/main/resources/shaders/${name}.cs").readText(), name)

// Have to keep the same name (oliveProgram) to get update on save to work
fun ApplicationBuilder.oliveProgram(init: Program.() -> Unit) {
  if (recordingEnabled) {
    program(init)
  } else {
    // TODO: Make watching shader files work
    oliveProgramOriginal(init = init)
  }
}

fun Program.liveComputeShader(name: String): ReadOnlyProperty<Any?, ComputeShader> {
  val shaderCode by
          watchingFile(File("src/main/resources/shaders/${name}.cs")) { file ->
            println("change")
            file.readText()
          }

  var cs: ComputeShader = ComputeShader.fromCode(shaderCode, name)

  if (!recordingEnabled) {
    var lastCompiledCode: String = shaderCode

    program.extend {
      if (shaderCode != lastCompiledCode) {
        cs.destroy()
        try {
          cs = ComputeShader.fromCode(shaderCode, name)
        } catch (e: Exception) {
          println("Shader compile failed: ${e.message}")
        }
        lastCompiledCode = shaderCode
      }
    }
  }

  return ReadOnlyProperty { _, _ -> cs }
}