mikeo_410
  1. 3.R
    1. 1.Rの常套句
    2. 2.いろいろ(R)
    3. 3.座標の引数(ベクトル、matrix、bind、list)
    4. 4.plot
    5. 5.RGL
    6. 6.ラグランジュの未定乗数法(Rsolnp)
    7. 7.常微分方程式の汎用解法(deSolve)

RGL

1. 楕円体を描く

わたしが使っているのは主に planes3d、lines3d で、単に線画を描いているにすぎません。

矩形などの基本図形を描くことも、ライティングなども知りません。

そんな中で地球儀を描こうと思って、楕円体を描くことだけは最初にやってみたことでした。

最初は、簡単に楕円体を描く関数が見つかって、何の苦もなく描けました。しばらくするとエラーが出て描画できなくなり、探すと別のパッケージに同じものがあるのを知って、パッケージ名を冠して使っていました。

しかし、いつの間にかこれも使えなくなっていました。その後、cdaパッケージにあることは分かったのですが現在何故かインストールできません。

私に必要なのは、楕円の一般的に挙げられている式の係数 a。b、c で原点を中心とした楕円が描ければ良いのです。また、回転楕円体で、赤道半径1として計算するので、a=b=1 が描ければ十分です。

止む無く、つなぎと思って以下のコードを使っています。

  1. ellipsoid <- function (
  2.             x, y, z,
  3.             a = 1, b=1, c=1,
  4.             phi=0, theta=0, psi=0,
  5.             subdivide = 3, smooth = TRUE, ...) {
  6.   if(missing(x)){
  7.     x<-0; y<-0; z<-0
  8.   } else if(missing(y) | missing(z)){
  9.     if(missing(y) & missing(z)){
  10.         if(is.list(x)){ y <- x$y; z <- x$z; x <- x$x
  11.         } else if(is.array(x)){ y <- x[,2]; z <- x[,3]; x <- x[,1] }
  12.         else {warning("引数のy,zは省略されているがxはリストでも配列でもない")}
  13.     } else {warning("引数が揃っていない")}
  14.   }
  15.   sphere <- rgl::subdivision3d(rgl::cube3d(...), subdivide)
  16.   class(sphere) <- c("mesh3d","shape3d")
  17.   norm <- sqrt( sphere$vb[1, ]^2 +
  18.                 sphere$vb[2, ]^2 +
  19.                 sphere$vb[3, ]^2 )
  20.   for (i in 1:3) sphere$vb[i, ] <- sphere$vb[i, ]/norm
  21.   sphere$vb[4, ] <- 1
  22.   sphere$normals <- sphere$vb
  23.   result <- rgl::scale3d(sphere, a,b,c)
  24.   rotM <- cpp_euler_passive(phi,theta,psi)
  25.   result <- rgl::rotate3d(result,matrix=rotM)
  26.   result <- rgl::translate3d(result, x,y,z)
  27.   invisible(result)
  28. }

C++で書かれている部分の代わりに

  1. cpp_euler_passive <- function(phi, theta, psi) {
  2.     Rot <- matrix(rep(0,9),nrow=3,ncol=3);
  3.     cosphi = cos(phi); cospsi = cos(psi); costheta = cos(theta);
  4.     sinphi = sin(phi); sinpsi = sin(psi); sintheta = sin(theta);
  5.     Rot[1,1] = cosphi*costheta*cospsi - sinphi*sinpsi;
  6.     Rot[1,2] = sinphi*costheta*cospsi + cosphi*sinpsi;
  7.     Rot[1,3] = -sintheta*cospsi;
  8.     Rot[2,1] = -cosphi*costheta*sinpsi - sinphi*cospsi;
  9.     Rot[2,2] = -sinphi*costheta*sinpsi + cosphi*cospsi;
  10.     Rot[2,3] = sintheta*sinpsi;
  11.     Rot[3,1] = cosphi*sintheta;
  12.     Rot[3,2] = sinphi*sintheta;
  13.     Rot[3,3] = costheta;
  14.     return(Rot);
  15.   }
2. 描画されているかどうかの確認

2種類の計算方法があるので、結果が同じかどうか描画して大まかな確認をしようとしました。後に指定した描画が上書きすると思い込んでいて、描画がされていないのでハマりました。

RGLの描画は、重なる部分を描画しないようになっているようです。一旦クリアして、個別に描画してみることが必要です。

3. 平面を描く

planes3d() は便利です。2Dのplot のabline() のように描画領域に合わせて表示してくれます。

一つ不便なのは、XY平面のように座標面を描くと軸が見にくくなることです。軸はアプリケーションで描いた図形の1つなので、その端も planes3d() は描画領域内と見なします。

これを回避するには矩形を描くことができれば良いのだと思います。


題目一覧へmikeo_410@hotmail.com(updated: 2022/12/27)