如何获取rgl::cylinder3d网格顶点对应的pts索引以按t_着色?
为球面李萨如曲线网格顶点分配对应t_值的颜色
要实现根据函数l中t_的值为cylinder3d生成的网格顶点分配颜色,核心是先找到每个网格顶点对应的原始pts数组的索引,再根据索引关联t_值映射颜色。具体步骤如下:
1. 理解cylinder3d的顶点结构
cylinder3d沿输入的pts路径生成网格:
- 每个
pts中的点对应sides个环绕顶点 - 当
closed=TRUE时,会重复pts的第一个点的sides个顶点以闭合曲线 - 最终顶点总数为
(nrow(pts) + 1) * sides(闭合时多一组起始点的顶点)
2. 生成顶点对应的pts索引
根据顶点排列规律,直接生成每个顶点对应的pts行索引:
n_pts <- nrow(pts) sides <- 30L # 前n_pts组对应pts[1]到pts[n_pts],最后一组重复pts[1]以闭合 vertex_indices <- rep(c(1:n_pts, 1), each = sides)
3. 根据t_值映射颜色
利用vertex_indices关联函数l中的t_向量,将t_值转换为颜色:
# 获取函数l中的t_向量(可修改函数直接返回,避免重复计算) g <- gcd(3, 2) t_ <- seq(0, 2*pi/g, length.out = 400L) # 将t_归一化到[0,1]区间,用于颜色映射 t_norm <- t_ / max(t_) # 用HSV颜色空间,根据t_值变化色相生成颜色 vertex_colors <- hsv(t_norm[vertex_indices], s = 1, v = 1)
4. 完整绘图代码
修改函数l使其同时返回pts和t_,再应用颜色绘制:
library(rgl) library(primes) l <- function(m1, m2, alpha = 0) { g <- gcd(m1, m2) t_ <- seq(0, 2*pi/g, length.out = 400L) list( pts = cbind( sin(m2 * t_) * cos(m1 * t_ - alpha * pi), sin(m2 * t_) * sin(m1 * t_ - alpha * pi), cos(m2 * t_) ), t = t_ ) } # 获取路径点和t_向量 result <- l(3, 2) pts <- result$pts t_ <- result$t # 生成网格 mesh <- addNormals(cylinder3d( pts, radius = 0.1, closed = TRUE, sides = 30L )) # 生成顶点索引和对应颜色 sides <- 30L vertex_indices <- rep(c(1:nrow(pts), 1), each = sides) t_norm <- t_ / max(t_) vertex_colors <- hsv(t_norm[vertex_indices], s = 1, v = 1) # 绘制带颜色的网格 shade3d(mesh, color = vertex_colors)
关键说明
- 修改函数
l同时返回pts和t_,避免重复计算,方便后续关联颜色 vertex_indices确保每个网格顶点与原始路径点一一对应,颜色完全匹配t_值的变化- 颜色映射可按需调整,比如改用
rainbow(n_pts)[vertex_indices]或其他调色板
内容的提问来源于stack exchange,提问作者Stéphane Laurent
相关产品推荐
相关产品推荐

