All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.math.perlin.ValueNoise1D.kt Maven / Gradle / Ivy

There is a newer version: 1.9.0
Show newest version
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)
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy