commonMain.ru.casperix.math.perlin.ValueNoise1D.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of math Show documentation
Show all versions of math Show documentation
Simple set of geometric and other types
package ru.casperix.math.perlin
import ru.casperix.misc.pow
import ru.casperix.math.function.Random1DFunction
import ru.casperix.math.function.random1dFunctions
import ru.casperix.math.function.Function1D
import ru.casperix.math.interpolation.float64.InterpolateDoubleFunction
import ru.casperix.math.interpolation.float64.cosineInterpolate
import kotlin.math.floor
import kotlin.math.pow
import kotlin.math.roundToInt
class ValueNoise1D(val persistence: Double = 0.5, val octaves: Int = 8, val interpolateFunction: InterpolateDoubleFunction = cosineInterpolate) {
val output: Function1D = { x ->
var total = 0.0
for (i in 0 until octaves) {
val frequency = 2.pow(i)
val amplitude = persistence.pow(i)
total += interpolate1d(x * frequency, random1dFunctions[i % 8]) * amplitude
}
total
}
private fun smoothNoise1d(x: Int, noise: Random1DFunction): Double {
return noise(x) / 2.0 + noise(x - 1) / 4.0 + noise(x + 1) / 4.0
}
private fun interpolate1d(x: Double, noise1dFunction: Random1DFunction): Double {
val integer_X = floor(x).roundToInt()
val fractional_X = x - integer_X
val v1 = smoothNoise1d(integer_X, noise1dFunction)
val v2 = smoothNoise1d(integer_X + 1, noise1dFunction)
return interpolateFunction(v1, v2, fractional_X)
}
}