-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Example] Add example/bitmasked.py (#905)
* [skip ci] [Example] Add example/bitmasked.py * [skip ci] fix indent * [skip ci] fix * [skip ci] enforce code format * [skip ci] apply review * [skip ci] apply reviews * [skip ci] fix random alias * [skip ci] use np.zeros to fix Co-authored-by: Taichi Gardener <taichigardener@gmail.com>
- Loading branch information
1 parent
e8dd87a
commit 4d228b9
Showing
2 changed files
with
48 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import taichi as ti | ||
import math | ||
|
||
ti.init(arch=ti.gpu) | ||
|
||
n = 256 | ||
x = ti.var(ti.f32) | ||
# `bitmasked` is a tensor that supports sparsity, in that each element can be | ||
# activated individually. (It can be viewed as `dense`, with an extra bit for each | ||
# element to mark its activation). Assigning to an element will activate it | ||
# automatically. Use struct-for syntax to loop over the active elements only. | ||
ti.root.bitmasked(ti.ij, (n, n)).place(x) | ||
|
||
|
||
@ti.kernel | ||
def activate(): | ||
# All elements in bitmasked is initially deactivated | ||
# Let's activate elements in the rectangle now! | ||
for i, j in ti.ndrange((100, 125), (100, 125)): | ||
x[i, j] = 233 # assign any value to activate the element at (i, j) | ||
|
||
|
||
@ti.kernel | ||
def paint_active_pixels(color: ti.f32): | ||
# struct-for syntax: loop over active pixels, inactive pixels are skipped | ||
for i, j in x: | ||
x[i, j] = color | ||
|
||
|
||
@ti.kernel | ||
def paint_all_pixels(color: ti.f32): | ||
# range-for syntax: loop over all pixels, no matter active or not | ||
for i, j in ti.ndrange(n, n): | ||
x[i, j] = color | ||
|
||
|
||
ti.root.deactivate_all() | ||
activate() | ||
|
||
gui = ti.GUI('bitmasked', (n, n)) | ||
for frame in range(10000): | ||
color = math.sin(frame * 0.05) * 0.5 + 0.5 | ||
paint_active_pixels(color) | ||
#paint_all_pixels(color) # try this and compare the difference! | ||
gui.set_image(x) | ||
gui.show() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters