其他
如何用很短的代码创造「秋日氛围感」?
运行代码,3D 漫游!
用体素搭建秋日小树林
import taichi as ti
from taichi.math import *
scene = Scene(voxel_edges=0, exposure=2)
# 创建场景,指定体素描边宽度和曝光值
scene.set_floor(0, (1.0, 1.0, 1.0))
# 地面高度
scene.set_background_color((0.5, 0.5, 0.4))
# 天空颜色
scene.set_directional_light((1, 1, -1), 0.2, (1, 0.8, 0.6))
# 光线方向和颜色
@ti.kernel
def initialize_voxels():
scene.set_voxel(vec3(0), 1, vec3(1))
# 在 (0, 0, 0) 加入一个白色 (1, 1, 1) 的体素!
initialize_voxels()
scene.finish()
基座
def create_block(pos, size, color, color_noise):
for I in ti.grouped(
ti.ndrange((pos[0], pos[0] + size[0]),
(pos[1], pos[1] + size[1]),
(pos[2], pos[2] + size[2]))):
scene.set_voxel(I, 1, color + color_noise * ti.random())
def initialize_voxels():
create_block(pos=ivec3(0, 0, 0),
size=ivec3(20, 40, 30),
color=vec3(0.3, 0.5, 0.3),
color_noise=vec3(0.1))
def initialize_voxels():
for i in range(4):
create_block(ivec3(-60, -(i + 1)**2 - 40, -60),
ivec3(120, 2 * i + 1, 120),
vec3(0.5 - i * 0.1) * vec3(1.0, 0.8, 0.6),
vec3(0.05 * (3 - i)))
树和落叶
def create_tree(pos, height, radius, color):
...
pos: 树根的位置
height:树的高度
radius:树叶半径 color:树叶颜色
def create_tree(pos, height, radius, color):
create_block(pos, ivec3(3, height - radius * 0.5, 3), vec3(0.7), vec3(0.3))
def create_leaves(pos, radius, color):
for I in ti.grouped(
ti.ndrange((-radius, radius), (-radius, radius),
(-radius, +radius))):
f = I / radius
d = vec2(f[0], f[2]).norm() # 到圆柱中轴线的距离
prob = max(0, 1 - d)**2
if ti.random() < prob:
scene.set_voxel(pos + I, 1, color + (ti.random() - 0.5) * 0.2)
def create_leaves(pos, radius, color):
for I in ti.grouped(
ti.ndrange((-radius, radius), (-radius, radius),
(-radius, +radius))):
f = I / radius
h = 0.5 - max(f[1], -0.5) * 0.5
d = vec2(f[0], f[2]).norm()
prob = max(0, 1 - d)**2 * h # xz mask
prob *= h # y mask
# noise
prob += ti.sin(f[0] * 5 + pos[0]) * 0.02
prob += ti.sin(f[1] * 9 + pos[1]) * 0.01
prob += ti.sin(f[2] * 10 + pos[2]) * 0.03
if prob < 0.1:
prob = 0.0
if ti.random() < prob:
scene.set_voxel(pos + I, 1, color + (ti.random() - 0.5) * 0.2)
prob = max((radius - vec2(i, j).norm()) / radius, 0)
prob = prob * prob
if ti.random() < prob * prob:
scene.set_voxel(pos + ivec3(i, 1, j), 1,
color + ti.random() * vec3(0.1))
create_tree(ivec3(45, -40, -45), 15, 10, vec3(0.8, 0.4, 0.1))
create_tree(ivec3(20, -40, 0), 45, 25, vec3(1.0, 0.4, 0.1))
create_tree(ivec3(30, -40, -20), 25, 15, vec3(1.0, 0.4, 0.1))
create_tree(ivec3(30, -40, 30), 45, 25, vec3(1.0, 0.4, 0.1))
树的部分收工!
围栏
def make_fence(start, direction, length):
color = vec3(0.5, 0.3, 0.2)
create_block(start, direction * length + ivec3(3, 2, 3), color, vec3(0.1))
fence_dist = 3
for i in range(length // fence_dist + 1):
create_block(start + direction * i * fence_dist + ivec3(1, -3, 1),
ivec3(1, 5, 1), color, vec3(0))
我也要玩!
欢迎扫码添加小助手
回复「创意大赛」
进入赛事交流群
⬇️