《The Book of Shader》笔记 : 第四节 - Shader中实现位移、旋转、缩放

前言

本节介绍了如何让画面中的图形进行位移,旋转缩放的操作。相比前一节,这节的内容似乎容易些,使用了一些大学高等代数中基本的矩阵运算。

正文

一. 位移示例
// ------------ Chapter_2_4_Main 1.glsl ------------ //

#ifdef GL_ES
precision mediump float;
#endif

float box(vec2 st, vec2 size) {
    size = vec2(0.5) - size* 0.5;
    vec2 uv = smoothstep(size, size + vec2(0.001), st);
    uv *= smoothstep(size, size + vec2(0.001), vec2(1.0) - st);
    return uv.x * uv.y;
}


float cross(vec2 st, float size) {
    return box(st, vec2(size, size/4.0)) + box(st, vec2(size/4.0, size));
}


void main() {
    vec2 uv = gl_FragCoord.xy / iResolution.xy;
    uv.x *= iResolution.x / iResolution.y;
    vec3 color = vec3(0.0);

    // To move the cross we move the space
    vec2 translate = vec2(cos(iTime), sin(iTime));

    uv += translate * 0.35;    // * //

    // Show the coordinates of the space on the background
    // color = vec3(uv.x, uv.y, 0.0);
    
    // Add the shape on the foreground
    color += vec3(cross(uv, 0.25));

    gl_FragColor = vec4(color, 1.0);    
}

位移操作,这里再输出图像之前,给整体的uv变量加上了一个位移向量,从而控制图形的移动。

// -------- Chapter_2_4_Main 2.glsl -------- //
在这里插入图片描述

二. 旋转、缩放示例
// ------------ Chapter_2_4_Main 2&3.glsl ------------ //

#ifdef GL_ES
precision mediump float;
#endif

#define PI 3.14159265359

// 缩放矩阵,输入值为x, y方向上放大的倍数
mat2 scale(vec2 scale){
    return mat2(scale.x, 0.0,
                0.0, scale.y);
}
// 旋转矩阵,若angle 为正,将图形逆时针旋转 angle °。
mat2 rotate2d(float angle) {
    return mat2(cos(angle), -sin(angle),
                sin(angle), cos(angle));
}

float box(vec2 st, vec2 size) {
    size = vec2(0.5) - size* 0.5;
    vec2 uv = smoothstep(size, size + vec2(0.001), st);
    uv *= smoothstep(size, size + vec2(0.001), vec2(1.0) - st);
    return uv.x * uv.y;
}


float cross(vec2 st, float size) {
    return box(st, vec2(size, size/4.0)) + box(st, vec2(size/4.0, size));
}


void main() {
    vec2 uv = gl_FragCoord.xy / iResolution.xy;
    uv.x *= iResolution.x / iResolution.y;
    vec3 color = vec3(0.0);
    
    // move space from the center to the vec2(0.0)
    uv -= vec2(0.5);
    
    // rotate the space
    // uv = rotate2d(sin(iTime) * PI) * uv;
    uv = scale(vec2(sin(iTime) + 1.0)) * rotate2d(iTime * PI) * uv;
    // move it back to the ori
    uv += vec2(0.5);
    color += vec3(cross(uv, 0.4));
    gl_FragColor = vec4(color, 1.0);    
}

在这里插入图片描述

文末

最后作者分享了于旋转位移相关的例子,先记着,待补。
https://www.shadertoy.com/view/4s2SRt

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值