如何在R中使用OpenGL加速有效地为图像栅格设置动画?

时间:2019-05-05 23:30:02

标签: r opengl rgl

这是这些问题的后续问题:

我想以交互方式查看2D细胞自动机的空间离散模拟输出。因此,我从简单开始,尝试了解绘制整数值矩阵的速度。我正在尝试使用rgl软件包,据我所知,该软件包是否提供R中(理论上)最快(?)的图形设备。

我正在用rgl尝试这种方法,但是帧速率是每秒30帧,但我发现它相当低(请参见下面的代码)。我的示例是从仅100x100的R矩阵绘制栅格图像。而且,我越来越忽悠了,不知道为什么。

这是我的方法(来自@ ben-bolker的回答),现在使用来自@ user2554330的反馈。

library(viridisLite)
library(rgl)

n_colours <- 100
n_row <- 500
n_col <- 500
vv <- viridis(n_colours)

setup <- function() {
  view3d(theta=0, phi=0)  ## head-on view
  #par3d(zoom=0.65, windowRect = c(0,0, n_col, n_row), viewport = c(0,0, n_col, n_row))
  par3d(zoom=0.65, windowRect = c(0,0, n_col, n_row), viewport = c(0,0, n_col, n_row))
}

# draw <- function(m) {
#   d <- dim(m)
#   surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]), 
#             color = vv[m],
#             smooth=FALSE, lit=FALSE  ## turn off smoothing/lights
#   )
# }

# draw2 <- function(m) {
#   par3d(skipRedraw = TRUE)  # but skip blank update
#   clear3d()
#   
#   d <- dim(m)
#   surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]), 
#             color = vv[m],
#             smooth=FALSE, lit=FALSE  ## turn off smoothing/lights
#   )
#   par3d(skipRedraw = FALSE) # Make sure image is shown
# }

draw3 <- function(colours) {
  par3d(skipRedraw = TRUE)  # but skip blank update
  clear3d()

  d <- dim(m)
  surface3d(x = 1:d[1], y = 1:d[2], z = matrix(0, d[1], d[2]), 
            color = colours,
            smooth=FALSE, lit=FALSE  ## turn off smoothing/lights
  )
  par3d(skipRedraw = FALSE) # Make sure image is shown
}

nframes <- 100

n_matrices <- list()
for(i in 1:nframes) {
  n_matrices[[i]] <- vv[matrix(sample(1:n_colours, n_row*n_col, replace = TRUE), nrow = n_row)]
}

setup()
# time <- system.time({
#   for (i in 1:nframes) {
#     draw(n_matrices[[i]])
#     par3d(skipRedraw = FALSE) # Make sure image is shown
#     
#     par3d(skipRedraw = TRUE)  # but skip blank update
#     pop3d()
#   }
#   par3d(skipRedraw = FALSE)
# })

time <- system.time({
  for (i in 1:nframes) {
    draw3(n_matrices[[i]])
  }
})


fps <- nframes/time[3]
fps

1 个答案:

答案 0 :(得分:1)

闪烁的原因也将减慢您的显示速度。您的pop3d()通话要求rgl重绘没有显示表面的图像。通过告诉rgl跳过重绘,您可以获得大约两倍的速度:

time <- system.time({
  for (i in 1:nframes) {
    draw(n_matrices[[i]])
    par3d(skipRedraw = FALSE) # Make sure image is shown

    par3d(skipRedraw = TRUE)  # but skip blank update
    pop3d()
  }
  par3d(skipRedraw = FALSE)
})