V
V
versolite322021-11-26 14:21:14
WebGL
versolite32, 2021-11-26 14:21:14

How to embed Math.Random in webgl?

There is such a script on webgl https://codepen.io/Khangeldy/pen/pgXNMZ
How to make variable values ​​random?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogachev, 2021-11-26
@sfi0zy

There is no standard rand function in glsl at our disposal. There is a popular implementation:

float rand(vec2 seed) {
    return fract(sin(dot(seed, vec2(12.9898,78.233))) * 43758.5453123);
}

It has been copied and pasted for years from project to project, and used when you need to randomize something.
But global constants must be just constants known at compile time. At an attempt to assign them a value calculated in some function, we will get compilation errors. Exceptions to this part in glsl are made only for special variables, in particular for uniform. They can be determined already in real time. It would be possible to randomize everything in main, and then pass all the values ​​to other functions as parameters, but it may be faster and more convenient to add more uniform variables, like:
var tuniform = {
  SEA_SPEED: {
    type: 'f',
    value: Math.random() * 10.0
  },
  time: {
// ...

in JS, and in the shader:
// Вместо
// const float SEA_SPEED = 0.8;
// используем
uniform float SEA_SPEED;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question