WebGL入门(三十)-利用层次模型实现机械臂模拟动画

1.demo效果

在这里插入图片描述

如上图,实现了模拟机械臂搬运方块动画

2.实现要点

2.1绘制各个模型块

在这个函数中绘制了底座,机械手臂1,2,3,还有要移动的方块和移动中的方块,在绘制这些模块时需要知道

<子节点模型变换> = <父节点的模型变换> x <自身模型变换>

这一关系式在示例代码中的体现是,创建一个全局变量g_modelMatrix保存模块的变换矩阵,先绘制父节点的模块,然后在这个矩阵的基础上添加自身的变换,之后绘制子节点模块

//声明模型变换矩阵和模型视图投影矩阵
var g_modelMatrix = new Matrix4()
var g_mvpMatrix = new Matrix4()

//绘制图形
function draw(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor) {

  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  gl.uniform3f(u_VerticesColor, 1.0, 0.4, 0.0)

  //绘制基座
  var baseHeight = 2.0 //基座的高度
  g_modelMatrix.setTranslate(0.0, -12.0, 0.0) //设置为平移矩阵,并沿y轴向下移动12
  drawBox(gl, n, 10.0, baseHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

  //方块
  var cubeHeight = 2.0 //方块厚度
  g_modelMatrix.setTranslate(0.0, -12.0, -16)
  drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)


  //第一节胳膊
  var arm1Length = 10.0 //第一节胳膊的长度
  g_modelMatrix.translate(0.0, baseHeight, 0.0)
  g_modelMatrix.rotate(g_body_angle, 0.0, 1.0, 0.0)
  drawBox(gl, n, 3.0, arm1Length, 3.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

  //第二节胳膊
  var arm2Length = 16.0
  g_modelMatrix.translate(0.0, arm1Length, 0.0) //移至arm1
  g_modelMatrix.rotate(g_arm_angle, 0.0, 0.0, 1.0)
  drawBox(gl, n, 4.0, arm2Length, 4.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

  //第三节胳膊
  var arm3Length = 10.0
  g_modelMatrix.translate(0.0, arm2Length, 0.0) //移至arm2
  g_modelMatrix.rotate(g_arm_angle, 0.0, 0.0, 1.0)
  drawBox(gl, n, 3.0, arm3Length, 3.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

  //手掌
  var palmLength = 2.0
  var handleLength = 8.0
  g_modelMatrix.translate(0.0, handleLength, 0.0) //移至arm3
  g_modelMatrix.rotate(0.0, 0.0, 1.0, 0.0)
  drawBox(gl, n, 6.0, palmLength, 6.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)


  //随手臂移动的方块
  if (g_isHandleCube) {
    gl.uniform3f(u_VerticesColor, 1.0, 0.0, 0.0)
    var cubeHeight = 2.0 //方块厚度
    g_modelMatrix.translate(0.0, cubeHeight, 0.0)
    drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)
  } else if (!g_isHandleCube && g_moveEnd) {
    g_modelMatrix.setTranslate(0.0, -12.0, -32)
    gl.uniform3f(u_VerticesColor, 1.0, 0.4, 0.0)
    var cubeHeight = 2.0 //方块厚度
    drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)
  }

}

2.2绘制方块函数

由于我们绘制所有的模块都是用了同一组顶点,所以每次绘制的时候需要把绘制前的模型矩阵保存下来,绘制完成后需要恢复

var g_matrixStack = [] //存储矩阵的数组
function pushMatrix(m) { //将矩阵压入栈
  var m2 = new Matrix4(m)
  g_matrixStack.push(m2)
}

function popMatrix() { //从栈中弹出矩阵
  return g_matrixStack.pop()
}

var g_normalMatrix = new Matrix4() //变换法向量矩阵

//绘制立方体
function drawBox(gl, n, width, height, depth, viewProjMatrix, u_MvpMatrix, u_NormalMatrix) {
  pushMatrix(g_modelMatrix) //备份变换前模型矩阵

  g_modelMatrix.scale(width, height, depth)
  //计算、设置模型视图投影矩阵
  g_mvpMatrix.set(viewProjMatrix)
  g_mvpMatrix.multiply(g_modelMatrix)
  gl.uniformMatrix4fv(u_MvpMatrix, false, g_mvpMatrix.elements)

  //计算、设置变换法向量矩阵
  g_normalMatrix.setInverseOf(g_modelMatrix)
  g_normalMatrix.transpose()
  gl.uniformMatrix4fv(u_NormalMatrix, false, g_normalMatrix.elements)

  //绘制
  gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0)
  g_modelMatrix = popMatrix() //将备份的模型矩阵赋值给全局模型矩阵
}

2.3动画函数

为了实现机械臂周而复始的做同样的运动,定义了全局变量g_times来记录动画次数,每次动画开始自加,到达指定次数时,一套完整动作执行完毕,相关参数全部恢复到初始,在一套动作中不同时段做不同变换,具体如下

//声明全局变量
var arm_step_angle = 1.0 //手臂每一次动画弯曲的角度
var body_step_angle = 3.0 //手臂整体每一次动画旋转角度
var g_body_angle = -90.0 //手臂整体的旋转角度
var g_arm_angle = -45.0 //手臂弯曲的角度
var g_isHandleCube = false
var g_moveEnd = false

var g_times = 0

function animate(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor) {
  g_times++
  if (g_times > 170) { //结束动画,数据重置
    g_times = 0
    arm_step_angle = 1.0 //手臂每一次动画弯曲的角度
    body_step_angle = 3.0 //手臂整体每一次动画旋转角度
    g_body_angle = -90.0 //手臂整体的旋转角度
    g_arm_angle = -45.0 //手臂弯曲的角度
    g_isHandleCube = false
    g_moveEnd = false
    g_modelMatrix.setTranslate(0.0, -12.0, 0.0) //模型矩阵恢复
  }

  if (g_times < 45) { //第二、第三手臂向下弯
    g_arm_angle -= arm_step_angle
  } else if (g_times <= 100) { //抓起方块整体旋转
    g_isHandleCube = true
    g_body_angle = g_body_angle + body_step_angle
  } else if (g_times <= 105) { //放下方块,抬起一点第二、第三手臂
    g_isHandleCube = false
    g_moveEnd = true
    g_arm_angle += arm_step_angle
  } else if (g_times <= 160) { //手臂整体旋转回来
    g_body_angle = g_body_angle - body_step_angle
    g_arm_angle += arm_step_angle
  } else if (g_times <= 165) { //手臂抬起
    g_arm_angle += arm_step_angle
  }

  draw(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor)
}

2.demo代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body>
  <!--通过canvas标签创建一个800px*800px大小的画布-->
  <canvas id="webgl" width="800" height="800"></canvas>
  <script type="text/javascript" src="./lib/cuon-matrix.js"></script>
  <script>
    //顶点着色器
    var VSHADER_SOURCE = '' +
      'attribute vec4 a_Position;\\n' + //声明attribute变量a_Position,用来存放顶点位置信息
      'attribute vec4 a_Normal;\\n' + //声明attribute变量a_Normal,用来存放法向量
      'uniform mat4 u_MvpMatrix;\\n' + //声明uniform变量u_MvpMatrix,用来存放模型视图投影组合矩阵
      'uniform mat4 u_NormalMatrix;\\n' + //声明uniform变量u_NormalMatrix,用来存放变换法向量矩阵
      'uniform vec3 u_VerticesColor;\\n' + //声明uniform变量u_VerticesColor,用来存放顶点颜色
      'varying vec4 v_Color;\\n' + //声明varying变量v_Color,用来向片元着色器传值顶点颜色信息
      'void main(){\\n' +
      '  gl_Position = u_MvpMatrix * a_Position;\\n' + //将模型视图投影组合矩阵与顶点坐标相乘赋值给顶点着色器内置变量gl_Position
      '  vec3 normal = normalize(vec3(u_NormalMatrix * a_Normal));\\n' + //对计算变换后的法向量并归一化处理
      '  vec3 lightDirection = normalize(vec3(0.0,0.5,0.7));\\n' + //声明光线方向
      '  float nDotL = max(dot(lightDirection, normal), 0.0);\\n' + //计算光线方向和法向量点积
      '  vec3 diffuse = u_VerticesColor * nDotL;\\n' + //计算平行光的颜色
      '  vec3 ambient = vec3(0.1);\\n' + //声明环境光颜色      
      '  v_Color = vec4(diffuse + ambient, 1.0);\\n' + //将颜色信息传给片元着色器,
      '}\\n'

    //片元着色器
    var FSHADER_SOURCE = '' +
      '#ifdef GL_ES\\n' +
      ' precision mediump float;\\n' + // 设置精度
      '#endif\\n' +
      'varying vec4 v_Color;\\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
      'void main(){\\n' +
      //将varying变量v_Color接收的颜色信息赋值给内置变量gl_FragColor
      ' gl_FragColor = v_Color;\\n' +
      '}\\n'

    //初始化着色器函数
    function initShader(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
      //创建顶点着色器对象
      var vertexShader = gl.createShader(gl.VERTEX_SHADER)
      //创建片元着色器对象
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
      //引入顶点、片元着色器源代码
      gl.shaderSource(vertexShader, VSHADER_SOURCE)
      gl.shaderSource(fragmentShader, FSHADER_SOURCE)
      //编译顶点、片元着色器
      gl.compileShader(vertexShader)
      gl.compileShader(fragmentShader)

      //创建程序对象program
      var program = gl.createProgram()
      //附着顶点着色器和片元着色器到program
      gl.attachShader(program, vertexShader)
      gl.attachShader(program, fragmentShader)
      //链接program
      gl.linkProgram(program)
      //使用program
      gl.useProgram(program)
      gl.program = program
      //返回程序program对象
      return program
    }

    function init() {
      //通过getElementById()方法获取canvas画布
      var canvas = document.getElementById('webgl')
      //通过方法getContext()获取WebGL上下文
      var gl = canvas.getContext('webgl')
      //初始化着色器
      if (!initShader(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('初始化着色器失败')
        return
      }

      // 设置canvas的背景色
      gl.clearColor(0.0, 0.0, 0.0, 1.0)

      //初始化顶点坐标和顶点颜色
      var n = initVertexBuffers(gl)

      setMatrixAndDraw(gl, n)

    }

    //设置矩阵并绘图
    function setMatrixAndDraw(gl, n) {

      //开启隐藏面消除
      gl.enable(gl.DEPTH_TEST)

      //清空颜色和深度缓冲区
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      //获取顶点着色器uniform变量u_MvpMatrix、u_NormalMatrix,u_VerticesColor的存储地址
      var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix')
      var u_NormalMatrix = gl.getUniformLocation(gl.program, 'u_NormalMatrix')
      var u_VerticesColor = gl.getUniformLocation(gl.program, 'u_VerticesColor')

      if (!u_MvpMatrix || !u_NormalMatrix || !u_VerticesColor) {
        console.log('获取u_MvpMatrix、u_NormalMatrix或u_VerticesColor存储地址失败')
        return
      }

      //设置视图投影矩阵
      var viewProjMatrix = new Matrix4()
      viewProjMatrix.setPerspective(50.0, 1.0, 1.0, 150.0)
      viewProjMatrix.lookAt(60.0, 20.0, 50.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

      //声明tick函数
      var tick = function () {
        animate(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor)
        requestAnimationFrame(tick)
      }
      tick() // 调用tick

    }



    //声明全局变量
    var arm_step_angle = 1.0 //手臂每一次动画弯曲的角度
    var body_step_angle = 3.0 //手臂整体每一次动画旋转角度
    var g_body_angle = -90.0 //手臂整体的旋转角度
    var g_arm_angle = -45.0 //手臂弯曲的角度
    var g_isHandleCube = false
    var g_moveEnd = false

    var g_times = 0

    function animate(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor) {
      g_times++
      if (g_times > 170) { //结束动画,数据重置
        g_times = 0
        arm_step_angle = 1.0 //手臂每一次动画弯曲的角度
        body_step_angle = 3.0 //手臂整体每一次动画旋转角度
        g_body_angle = -90.0 //手臂整体的旋转角度
        g_arm_angle = -45.0 //手臂弯曲的角度
        g_isHandleCube = false
        g_moveEnd = false
        g_modelMatrix.setTranslate(0.0, -12.0, 0.0) //模型矩阵恢复
      }

      if (g_times < 45) { //第二、第三手臂向下弯
        g_arm_angle -= arm_step_angle
      } else if (g_times <= 100) { //抓起方块整体旋转
        g_isHandleCube = true
        g_body_angle = g_body_angle + body_step_angle
      } else if (g_times <= 105) { //放下方块,抬起一点第二、第三手臂
        g_isHandleCube = false
        g_moveEnd = true
        g_arm_angle += arm_step_angle
      } else if (g_times <= 160) { //手臂整体旋转回来
        g_body_angle = g_body_angle - body_step_angle
        g_arm_angle += arm_step_angle
      } else if (g_times <= 165) { //手臂抬起
        g_arm_angle += arm_step_angle
      }

      draw(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor)
    }



    function initArrayBuffer(gl, data, num, type, attribute) {
      //创建缓冲区对象
      var buffer = gl.createBuffer()
      //将顶点坐标和顶点颜色信息写入缓冲区对象
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
      gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW)

      //获取顶点着色器attribute变量存储地址, 分配缓存并开启
      var a_Attribute = gl.getAttribLocation(gl.program, attribute)
      gl.vertexAttribPointer(a_Attribute, num, type, false, 0, 0)
      gl.enableVertexAttribArray(a_Attribute)

      return true
    }
    //声明模型变换矩阵和模型视图投影矩阵
    var g_modelMatrix = new Matrix4()
    var g_mvpMatrix = new Matrix4()

    //绘制图形
    function draw(gl, n, viewProjMatrix, u_MvpMatrix, u_NormalMatrix, u_VerticesColor) {

      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
      gl.uniform3f(u_VerticesColor, 1.0, 0.4, 0.0)

      //绘制基座
      var baseHeight = 2.0 //基座的高度
      g_modelMatrix.setTranslate(0.0, -12.0, 0.0) //设置为平移矩阵,并沿y轴向下移动12
      drawBox(gl, n, 10.0, baseHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

      //方块
      var cubeHeight = 2.0 //方块厚度
      g_modelMatrix.setTranslate(0.0, -12.0, -16)
      drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)


      //第一节胳膊
      var arm1Length = 10.0 //第一节胳膊的长度
      g_modelMatrix.translate(0.0, baseHeight, 0.0)
      g_modelMatrix.rotate(g_body_angle, 0.0, 1.0, 0.0)
      drawBox(gl, n, 3.0, arm1Length, 3.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

      //第二节胳膊
      var arm2Length = 16.0
      g_modelMatrix.translate(0.0, arm1Length, 0.0) //移至arm1
      g_modelMatrix.rotate(g_arm_angle, 0.0, 0.0, 1.0)
      drawBox(gl, n, 4.0, arm2Length, 4.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

      //第三节胳膊
      var arm3Length = 10.0
      g_modelMatrix.translate(0.0, arm2Length, 0.0) //移至arm2
      g_modelMatrix.rotate(g_arm_angle, 0.0, 0.0, 1.0)
      drawBox(gl, n, 3.0, arm3Length, 3.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)

      //手掌
      var palmLength = 2.0
      var handleLength = 8.0
      g_modelMatrix.translate(0.0, handleLength, 0.0) //移至arm3
      g_modelMatrix.rotate(0.0, 0.0, 1.0, 0.0)
      drawBox(gl, n, 6.0, palmLength, 6.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)


      //随手臂移动的方块
      if (g_isHandleCube) {
        gl.uniform3f(u_VerticesColor, 1.0, 0.0, 0.0)
        var cubeHeight = 2.0 //方块厚度
        g_modelMatrix.translate(0.0, cubeHeight, 0.0)
        drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)
      } else if (!g_isHandleCube && g_moveEnd) {
        g_modelMatrix.setTranslate(0.0, -12.0, -32)
        gl.uniform3f(u_VerticesColor, 1.0, 0.4, 0.0)
        var cubeHeight = 2.0 //方块厚度
        drawBox(gl, n, 10.0, cubeHeight, 10.0, viewProjMatrix, u_MvpMatrix, u_NormalMatrix)
      }

    }

    var g_matrixStack = [] //存储矩阵的数组
    function pushMatrix(m) { //将矩阵压入栈
      var m2 = new Matrix4(m)
      g_matrixStack.push(m2)
    }

    function popMatrix() { //从栈中弹出矩阵
      return g_matrixStack.pop()
    }

    var g_normalMatrix = new Matrix4() //变换法向量矩阵

    //绘制立方体
    function drawBox(gl, n, width, height, depth, viewProjMatrix, u_MvpMatrix, u_NormalMatrix) {
      pushMatrix(g_modelMatrix) //备份变换前模型矩阵

      g_modelMatrix.scale(width, height, depth)
      //计算、设置模型视图投影矩阵
      g_mvpMatrix.set(viewProjMatrix)
      g_mvpMatrix.multiply(g_modelMatrix)
      gl.uniformMatrix4fv(u_MvpMatrix, false, g_mvpMatrix.elements)

      //计算、设置变换法向量矩阵
      g_normalMatrix.setInverseOf(g_modelMatrix)
      g_normalMatrix.transpose()
      gl.uniformMatrix4fv(u_NormalMatrix, false, g_normalMatrix.elements)

      //绘制
      gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0)
      g_modelMatrix = popMatrix() //将备份的模型矩阵赋值给全局模型矩阵
    }

    //初始化顶点坐标和顶点颜色
    function initVertexBuffers(gl) {

      var v0 = [0.5, 1.0, 0.5]
      var v1 = [-0.5, 1.0, 0.5]
      var v2 = [-0.5, 0.0, 0.5]
      var v3 = [0.5, 0.0, 0.5]
      var v4 = [0.5, 0.0, -0.5]
      var v5 = [0.5, 1.0, -0.5]
      var v6 = [-0.5, 1.0, -0.5]
      var v7 = [-0.5, 0.0, -0.5]

      //顶点
      var vertices = new Float32Array([
        ...v0, ...v1, ...v2, ...v3, // 前
        ...v0, ...v3, ...v4, ...v5, // 右
        ...v0, ...v5, ...v6, ...v1, // 上
        ...v1, ...v6, ...v7, ...v2, // 左
        ...v7, ...v4, ...v3, ...v2, // 下
        ...v4, ...v7, ...v6, ...v5 // 后
      ])

      var font = [0.0, 0.0, 1.0]
      var back = [0.0, 0.0, -1.0]
      var left = [-1.0, 0.0, 0.0]
      var right = [1.0, 0.0, 0.0]
      var top = [0.0, 1.0, 0.0]
      var down = [0.0, -1.0, 0.0]
      // 法向量
      var normals = new Float32Array([
        ...font, ...font, ...font, ...font, // v0-v1-v2-v3 前
        ...right, ...right, ...right, ...right, // v0-v3-v4-v5 右
        ...top, ...top, ...top, ...top, // v0-v5-v6-v1 上
        ...left, ...left, ...left, ...left, // v1-v6-v7-v2 左
        ...down, ...down, ...down, ...down, // v7-v4-v3-v2 下
        ...back, ...back, ...back, ...back, // v4-v7-v6-v5 后
      ])

      // 绘制的索引
      var indices = new Uint8Array([
        0, 1, 2, 0, 2, 3, // 前
        4, 5, 6, 4, 6, 7, // 右
        8, 9, 10, 8, 10, 11, // 上
        12, 13, 14, 12, 14, 15, // 左
        16, 17, 18, 16, 18, 19, // 下
        20, 21, 22, 20, 22, 23 // 后
      ])

      if (!initArrayBuffer(gl, vertices, 3, gl.FLOAT, 'a_Position')) {
        return -1
      }

      if (!initArrayBuffer(gl, normals, 3, gl.FLOAT, 'a_Normal')) {
        return -1
      }

      //创建缓冲区对象
      var indexBuffer = gl.createBuffer()

      //将顶点索引写入缓冲区对象
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW)

      return indices.length

    }

    init()
  </script>
</body>

</html>

© 版权声明
THE END
喜欢就支持一下吧
点赞668 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容