登峰造极境

  • WIN
    • CSharp
    • JAVA
    • OAM
    • DirectX
    • Emgucv
  • UNIX
    • FFmpeg
    • QT
    • Python
    • Opencv
    • Openwrt
    • Twisted
    • Design Patterns
    • Mysql
    • Mycat
    • MariaDB
    • Make
    • OAM
    • Supervisor
    • Nginx
    • KVM
    • Docker
    • OpenStack
  • WEB
    • ASP
    • Node.js
    • PHP
    • Directadmin
    • Openssl
    • Regex
  • APP
    • Android
  • AI
    • Algorithm
    • Deep Learning
    • Machine Learning
  • IOT
    • Device
    • MSP430
  • DIY
    • Algorithm
    • Design Patterns
    • MATH
    • X98 AIR 3G
    • Tucao
    • fun
  • LIFE
    • 美食
    • 关于我
  • LINKS
  • ME
Claves
长风破浪会有时,直挂云帆济沧海
  1. 首页
  2. Programming
  3. babylon.js
  4. 正文

Babylonjs顶点上色

2025-05-08

一、应用场景

如果想实现不给Mesh上材质,且还想让Mesh有颜色,那么可以考虑使用顶点着色方案。通常应用与一下场景:

  • Mesh全合并后,上色问题。比如rvt/ifc格式有很多mesh,会引起dc问题,所以可以全部合并Mesh,后通过顶点上色的方案优化帧率。

二、技术测试

下面的代码,创建了8个顶点,给顶点分别上色后,实现了各个三角面的固定颜色、渐变色效果。

Donut | Babylon.js Playground

var createScene = function () {
    var scene = new BABYLON.Scene(engine);
    var light = new BABYLON.DirectionalLight("direct", new BABYLON.Vector3(0, 0, 10), scene);
    var light1 = new BABYLON.DirectionalLight("direct", new BABYLON.Vector3(0, 0, -10), scene);

    var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(0, 0, 0), scene);
    camera.setPosition(new BABYLON.Vector3(0, 5, -30));
    camera.attachControl(canvas, true);

    var mat = new BABYLON.StandardMaterial('mat'); //这个StandardMaterial 主要打开背面剔除,没其它作用(不显示背面的话,不要也行)
    //mat.diffuseColor = new BABYLON.Color3(0, 1, 1); //其漫反射颜色(diffuseColor)直接决定物体基础色。
    mat.backFaceCulling = false; //打开背面剔除
    mat.vertexColors = true;
    
    //Create a custom mesh  
    var customMesh = new BABYLON.Mesh("custom", scene);
    customMesh.material = mat;

    //Set arrays for positions and indices
    var positions = [-5, 2, -3, -7, -2, -3, -3, -2, -3, 5, 2, 3, 7, -2, 3, 3, -2, 3, -5, 2, -3, -3, -2, -3, 0, 0, -3]; //9个顶点
    var indices = [0, 1, 2, 3, 4, 5, 6, 7, 8]; //3个三角形
    var colors = [1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; //9个顶点,各个顶点的RGBA值

    //Empty array to contain calculated values
    var normals = [];

    var vertexData = new BABYLON.VertexData();
    BABYLON.VertexData.ComputeNormals(positions, indices, normals);

    //Assign positions, indices and normals to vertexData
    vertexData.positions = positions;
    vertexData.indices = indices;
    vertexData.normals = normals;
    vertexData.colors = colors;

    //Apply vertexData to custom mesh
    vertexData.applyToMesh(customMesh);

    return scene;
};
标签: 暂无
最后更新:2025-05-08

代号山岳

知之为知之 不知为不知

点赞
< 上一篇
下一篇 >

COPYRIGHT © 2099 登峰造极境. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备14031139号-5

川公网安备51012202000587号