Skip to content

taichi-dev/taichi_glsl

Repository files navigation

Taichi GLSL

Taichi GLSL is an extension library of the Taichi Programming Language, which provides a set of useful helper functions including but not limited to:

  1. Handy scalar functions like clamp, smoothstep, mix, round.
  2. GLSL-alike vector functions like normalize, distance, reflect.
  3. Well-behaved random generators including randUnit3D, randNDRange.
  4. Handy vector and matrix initializer: vec and mat.
  5. Handy vector component shuffle accessor like v.xy.
  6. Handy field sampler including bilerp and sample.
  7. Useful physics helper functions like boundReflect.
  8. Shadertoy-alike inputed GUI base class Animation.

[Clike me for documentation]

Build Status Documentation Status Coverage Status Downloads Latest Release

Installation

Install Taichi and Taichi GLSL with pip:

# Python 3.6/3.7/3.8 (64-bit)
pip install taichi taichi_glsl

How to play

First, import Taichi and Taichi GLSL:

import taichi as ti
import taichi_glsl as ts

Then, use ts.xxx helper functions in your Taichi kernels like this:

@ti.kernel
def kern():
  a = ts.vec(2.2, -3.3)   # deduced to be vec2
  b = ts.normalize(a)     # get normalized vector
  c = ts.clamp(a)         # element-wise, clamp to range [0, 1]
  d = int(a)              # cast to ivec2, vector of integers
  print(b, c, d)          # [0.554700, -0.832050] [1.000000, 0.000000] [2, -3]

Hints

If you don't like the ts. prefix, import using:

from taichi_glsl import *

@ti.kernel
def kern():
  a = vec(2.33, 6.66)
  b = normalize(a)
  ...

Note that this will import taichi as name ti as well.


vec2, vec3 and vec4 are simply vec in Taichi GLSL:

v = vec(2.0, 3.0)            # vec2
v = vec(2.0, 3.0, 4.0)       # vec3
v = vec(2.0, 3.0, 4.0, 5.0)  # vec4
v = vec(2, 3)                # ivec2 (since 2 is an integer)

Thanks to the python syntax of vec(*args).

Example

The following codes shows up an Shadertoy-style rainbow UV in the window:

import taichi as ti
import taichi_glsl as ts

ti.init()


class MyAnimation(ts.Animation):
    def on_init(self):
        self.img = ti.Vector(3, ti.f32, (512, 512))
        self.define_input()

    @ti.kernel
    def on_render(self):
        for I in ti.grouped(self.img):
            uv = I / self.iResolution
            self.img[I] = ti.cos(uv.xyx + self.iTime +
                                 ts.vec(0, 2, 4)) * 0.5 + 0.5


MyAnimation().start()

Check out more examples in the examples/ folder.

Links