threejs gpu pick

package.json

{
  "name": "gpu-pick-code",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "dependencies": {
    "three": "0.110.0",
    "three-orbitcontrols": "2.110.3"
  },
  "devDependencies": {
    "html-webpack-plugin": "4.5.0",
    "ts-loader": "6.2.2",
    "typescript": "4.3.5",
    "webpack": "4.42.1",
    "webpack-cli": "3.3.12",
    "webpack-dev-server": "3.11.2"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "noEmit": true,
        "module": "esnext",
        "target": "es6",
        "lib": ["ES2019","dom"],
        "sourceMap": true,
        "moduleResolution": "node",
        "forceConsistentCasingInFileNames": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "skipLibCheck": true,
        "suppressImplicitAnyIndexErrors": true,
        "experimentalDecorators": true,
        "noUnusedLocals": true,
        "downlevelIteration": true,
        "strict": true,
        "strictPropertyInitialization": false,
        "allowSyntheticDefaultImports": true,
        "skipDefaultLibCheck": true
    },
    "exclude": [
        "node_modules",
    ]
}

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');

module.exports = {
    devtool: 'source-map',
    plugins: [
        new HtmlWebpackPlugin({
            template: resolve('./index.html')
        })
    ],
    resolve: {
        extensions: ['.ts', '.js']
    },
    module:{
            rules:[
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true,
                        experimentalWatchApi: true,
                    }
                },
            ],
        },
    devServer: {
        compress: true,
        stats: {
            assets: false,
            builtAt: true,
            modules: false,
            entrypoints: false,
            /**
             * ts-node transpileOnly: true
             * if you enable this option, webpack 4 will give you "export not found" warnings any time you re-export a type:
             * The reason this happens is that when typescript doesn't do a full type check, 
             * it does not have enough information to determine whether an imported name is a type or not, 
             * so when the name is then exported, typescript has no choice but to emit the export. 
             * Fortunately, the extraneous export should not be harmful, so you can just suppress these warnings:
             */
            // warningsFilter: /export .* was not found in/
        },
    },
};

src/three-orbitcontrols.d.ts

declare module 'three-orbitcontrols' {
    class OrbitControls {
        constructor( camera: THREE.Camera, dom: HTMLElement );
    }

   export = OrbitControls;
}

src/index.ts

import * as THREE from 'three';
import OrbitControls from 'three-orbitcontrols';

// 創(chuàng)建相機(jī)
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// 創(chuàng)建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

// 創(chuàng)建場(chǎng)景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeaeaea);

// 創(chuàng)建mesh
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

const edges = new THREE.EdgesGeometry(geometry);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0x000000 });
const line = new THREE.LineSegments(edges, lineMaterial);
scene.add(line);

// 添加控制器
new OrbitControls(camera, document.body);

function animate() {
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
}
animate();


const w = 20; // gpu拾取寬度
const pickingTexture = new THREE.WebGLRenderTarget(w, w);
const pickingBuffer = new Uint8Array(4 * w * w);

const canvas = document.querySelector('canvas')!;
const ctx = canvas.getContext('2d')!;


let lock = false;
document.addEventListener('mousedown', () => {
    lock = true;
    renderer.setRenderTarget(null);
    document.body.className = 'lock';
});

document.addEventListener('mouseup', () => {
    lock = false;
    setTimeout(() => document.body.className = '', 100);
});

document.addEventListener('mousemove', (event) => {
    if (lock) {
        return;
    }
    // 移動(dòng)畫布中的選中框
    const x = event.clientX - 10;
    const y = event.clientY - 10;
    const pick = document.querySelector('.pick') as HTMLElement;
    pick.style.transform = `translate(${x}px, ${y}px)`;

    // threejs拾取場(chǎng)景中的圖像
    camera.setViewOffset(window.innerWidth, window.innerHeight, x, y, w, w);
    renderer.setRenderTarget(pickingTexture);
    renderer.render(scene, camera);
    pickingBuffer.fill(0);
    renderer.readRenderTargetPixels(pickingTexture, 0, 0, w, w, pickingBuffer);
    camera.clearViewOffset();

 
    // threejs中y坐標(biāo)與canvas中的y坐標(biāo)不一致 故要做轉(zhuǎn)化
    const unit8ArrayGroup = [] as Uint8Array[];
    for (let i = 0; i < pickingBuffer.length; i += 4 * w) {
        unit8ArrayGroup.push(pickingBuffer.slice(i, i + 4* w));
    }
    const mirror = unit8ArrayGroup.reverse().reduce((arr, u) => {
        arr.push(...u);
        return arr;
    }, [] as number[]);

    // 將數(shù)據(jù)填充到canvas中
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    for (let i = 0; i < mirror.length; i++ ) {
        data[i] = mirror[i];
    }
    ctx.putImageData(imageData, 0, 0);
});
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市乐埠,隨后出現(xiàn)的幾起案子亏较,更是在濱河造成了極大的恐慌愈犹,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件前联,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)吗浩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來没隘,“玉大人懂扼,你說我怎么就攤上這事∮移眩” “怎么了阀湿?”我有些...
    開封第一講書人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)瑰妄。 經(jīng)常有香客問我陷嘴,道長(zhǎng),這世上最難降的妖魔是什么间坐? 我笑而不...
    開封第一講書人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任灾挨,我火速辦了婚禮,結(jié)果婚禮上竹宋,老公的妹妹穿的比我還像新娘劳澄。我一直安慰自己,他們只是感情好蜈七,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開白布秒拔。 她就那樣靜靜地躺著,像睡著了一般飒硅。 火紅的嫁衣襯著肌膚如雪砂缩。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評(píng)論 1 305
  • 那天狡相,我揣著相機(jī)與錄音梯轻,去河邊找鬼。 笑死尽棕,一個(gè)胖子當(dāng)著我的面吹牛喳挑,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼伊诵,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼单绑!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起曹宴,我...
    開封第一講書人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤搂橙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后笛坦,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體区转,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年版扩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了废离。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡礁芦,死狀恐怖蜻韭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情柿扣,我是刑警寧澤肖方,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站未状,受9級(jí)特大地震影響俯画,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜娩践,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一活翩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧翻伺,春花似錦、人聲如沸沮焕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽峦树。三九已至辣辫,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間魁巩,已是汗流浹背急灭。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谷遂,地道東北人葬馋。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親畴嘶。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蛋逾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容