You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Shader中的step函数相关代码转换为JavaScript代码?

GLSL step函数转JS实现说明

GLSL的step函数遵循如下规则:

  • 接收两个参数edge(阈值)和x(待判断值),当x >= edge时返回1,否则返回0
  • 如果参数是同维度向量,会逐分量执行上述判断,返回相同维度的结果向量

你给出的Shader代码vec2 cmp = step(t_max.xy, t_max.yx);实际是逐分量做判断:

  • cmp的x分量:判断t_max.y >= t_max.x,符合返回1否则返回0
  • cmp的y分量:判断t_max.x >= t_max.y,符合返回1否则返回0

实现方案

你按索引0对应x、索引1对应y用数组存二维向量的话,可以选以下任意一种实现:

  1. 通用step函数实现(适合多处需要step运算的场景)
// 支持标量、二维向量的step函数
function step(edge, x) {
  // 标量运算逻辑
  if (typeof edge === 'number' && typeof x === 'number') {
    return x >= edge ? 1 : 0
  }
  // 二维向量逐分量运算逻辑
  if (Array.isArray(edge) && Array.isArray(x) && edge.length === 2 && x.length === 2) {
    return [
      x[0] >= edge[0] ? 1 : 0,
      x[1] >= edge[1] ? 1 : 0
    ]
  }
  throw new Error('参数类型不匹配,仅支持标量或二维向量')
}

// 直接调用即可得到结果
const cmp = step([t_max[0], t_max[1]], [t_max[1], t_max[0]])
  1. 特定场景简写(仅针对你当前的运算需求,无需封装通用函数)
const cmp = [
  t_max[1] >= t_max[0] ? 1 : 0,
  t_max[0] >= t_max[1] ? 1 : 0
]

内容的提问来源于stack exchange,提问作者trshmanx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 03:06:04