Exercises from the Shader Scriptures

This winter break, I have dedicated my time to delving into the world of shaders. I am currently faced with a challenging exercise:

y = sin(x);

Explore the exercises below and observe the results:

  • Introduce time (u_time) into the equation before calculating sin. Visualize the movement along x.

Any tips on how to execute this?

Answer №1

To create a sine gradient effect, you'll require 2 uniform variables in your vertex shader: the resolution of the viewport (u_resolution) and the time (u_time) in seconds:

uniform vec2 u_resolution;
uniform float u_time;

The x value can be obtained by the x coordinate of the fragment. Map the x coordinate to the range [0, 2*PI]:

vec2 st = gl_FragCoord.xy/u_resolution.xy;
float x = st.x * 2.0 * 3.141529;

Next, calculate the value of y. Utilize the sin function which represents the Sine value:

float y = sin(x + u_time);

Assign the color channels of the fragment based on the value of y. Ensure that y is mapped from the range [-1, 1] to [0, 1]:

gl_FragColor = vec4(vec3(y*0.5+0.5), 1.0);

The end result will be a visually appealing sine gradient that moves from right to left:

var container, camera, scene, renderer, uniforms;

init();
animate();

function init() {
    container = document.getElementById( 'container' );
    camera = new THREE.Camera();
    camera.position.z = 1;
    scene = new THREE.Scene();
    var geometry = new THREE.PlaneBufferGeometry( 2, 2 );

    uniforms = {
        u_time: { type: "f", value: 1.0 },
        u_resolution: { type: "v2", value: new THREE.Vector2() }
    };

    var material = new THREE.ShaderMaterial( {
        uniforms: uniforms,
        vertexShader: document.getElementById( 'vertexShader' ).textContent,
        fragmentShader: document.getElementById( 'fragmentShader' ).textContent
    } );
    var mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    container.appendChild( renderer.domElement );
    (window.onresize = function() {
        renderer.setSize( window.innerWidth, window.innerHeight );
        uniforms.u_resolution.value.x = renderer.domElement.width;
        uniforms.u_resolution.value.y = renderer.domElement.height;
    })();

}

function animate(delta_ms) {
    requestAnimationFrame( animate );
    uniforms.u_time.value = delta_ms / 1000.0;
    renderer.render( scene, camera );
}
<script id="vertexShader" type="x-shader/x-vertex">
void main() {
    gl_Position = vec4( position, 1.0 );
}
</script>

<script id="fragmentShader" type="x-shader/x-fragment">
uniform vec2 u_resolution;
uniform float u_time;

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy;

    float x = st.x * 2.0 * 3.141529;
    float y = sin(x + u_time);

    gl_FragColor = vec4(vec3(y*0.5+0.5), 1.0);
}
</script>

<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>

Answer №2

This is my view on how it could be achieved:

y = sin(u_time + x);

Observing the sinusoidal wave oscillating horizontally along the x-axis.

Elaboration: u_time represents the duration in seconds since the shader launch. By incorporating this variable, we can add it to the x value prior to performing the sine calculation, resulting in the appearance of the wave advancing along the x-axis.

To set it up, you can modify the text just beneath the graph.https://i.sstatic.net/iId3G.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips on setting the time format in dimple.js

Trying to create a multi-line graph using dimple.js based on some sample code. I have flattened my JSON into an array and thought I had the code down, but I'm stuck. I am including these 2 libraries (using cloudflare dimple for security reasons): &l ...

The image will remain hidden until it is fully loaded and ready to be displayed

I am currently working on a script that involves displaying a loading icon until an image is fully loaded, at which point the loading icon should disappear and the image should be shown. Unfortunately, my current code is not working as intended. Here is a ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

Using a jQuery UI dialog for multiple checkbox selection. The post array cannot be saved for a multi-select until the dialog is opened

CSS <td class="cell"> <a class="opener" id="opener_'.$iterator.'" href="#" rel="#type_dialog_<?= $iterator; ?>">Click here</a> <div id="type_dialog_<?= $iterator; ?>" name="t ...

Choosing multiple items using ng-checked and ng-model in AngularJS

I am working with an Ionic application and encountering a minor issue, much like AngularJS. <ion-list class="list-inset subcategory" ng-repeat="item in shops"> <ion-checkbox class="item item-divider item-checkbox-right" ng-model="selectAll" ...

DANGEROUS EVALUATION: Tips for Safe Replacement

Looking for a safer alternative to the code below which utilizes eval. The script creates pop-up windows based on different classes. /* exported popup_default , popup_help , popup_sitemap , popup_footerlinks */ var matchClass = ['popup_default' ...

React Data Filtering Techniques

I'm currently facing an issue with the if statement in my Action component. I'm struggling to figure out how to handle the case when an item is not found in the data from a JSON file. I have a Filtering function in a Context that I am using globa ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Ways to enable an Angular 5 web application to launch in multiple tabs within a single browser

Is there a way to open an Angular 5 app in multiple tabs of Chrome? Are there any methods or caching processes that can assist with this task? ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

Locate all posts associated with the specified User ID

Using mongoose, I am able to populate the "Post Schema" with relevant information about users who create the posts. postModule.js const mongoose = require('mongoose'); const postSchema = mongoose.Schema({ title:String, description:String, date ...

Currently experimenting with jQuery in conjunction with the reddit API to generate individual divs for every post

Issue with displaying post titles, URLs, and permalinks separately. Need them to display together for each post. See the code below: $(document).ready(function() { $.getJSON( "http://www.reddit.com/r/pics.json?jsonp=?", function foo(data) { ...

Contrasting results when logging an element in Chrome versus IE

Running the script below in Internet Explorer gives the expected output for console.log(target_el): <div class="hidden"></div> However, when run in Chrome, the output changes to: <div class="visible"></div> To add a humorous twi ...

Instruct Smarty to display the block exactly as it is

Struggling to inline some JavaScript code into the Smarty template files due to the {ldelim} {rdelim} markers. Is there a way to instruct Smarty to disregard the markup and just output it as is? Any similar approach like CDATA blocks in XML? Just demonstr ...

How can components be utilized with v-edit-dialog?

Hey there, I've been exploring the v-edit-dialog component offered by Vuetify and had a query about its implementation. Currently, I'm structuring my v-data-table in a way where I'm importing a component with props into a template slot. The ...

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...