1 Star 0 Fork 1

guohuacai/threejs

forked from 师启明/threejs 
Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
28dianyun.html 15.51 KB
Copy Edit Raw Blame History
shiqiming authored 2024-02-06 13:56 . 123
<!--本课视频地址 15 -->
<!DOCTYPE html>
<html>
<head>
<title>动力IT实训-threejs-015</title>
<meta charset="UTF-8" />
<!-- <script type="module" charset="UTF-8" src="../../libs/three.js/Three.js"></script> -->
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script type="x-shader/x-vertex" id="vertexshader">
attribute float scale;
uniform mat4 myR;
void main() {
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
//gl_PointSize = scale * ( 300.0 / - mvPosition.z )
gl_PointSize = 1.0;
//gl_PointSize = myR;
gl_Position = projectionMatrix * mvPosition;
}
</script>
<script type="x-shader/x-fragment" id="fragmentshader">
uniform vec3 color;
void main() {
if ( length( gl_PointCoord - vec2( 0.5, 0.5 ) ) > 0.5 ) discard;
gl_FragColor = vec4( color, 1.0 );
}
</script>
<script type="importmap">
{
"imports": {
"three": "./src/Three.js"
}
}
</script>
<!--我们将把threejs渲染的效果显示在这个div中-->
<div id="puiedu-webgl-output"></div>
<div id="myStats"></div>
<script type="module">
import dat from "./libs/lil-gui.module.min.js";
import * as THREE from "./src/Three.js";
import { OrbitControls } from "./jsm/controls/OrbitControls.js";
import Stats from "./libs/stats.module.js";
var stats = new Stats();
document.getElementById("myStats").appendChild(stats.domElement);
var myColor = new THREE.Color(0x7777ff);
var scene = new THREE.Scene();
// scene.background = new THREE.Color(0x333333)
scene.background = new THREE.Color(0x000000);
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
camera.position.x = 10;
camera.position.y = 10;
camera.position.z = 10;
camera.up = new THREE.Vector3(0, 0, 1);
camera.lookAt(scene.position);
scene.add(camera);
var render = new THREE.WebGLRenderer();
render.setClearColor(new THREE.Color(0xffffff));
render.setSize(window.innerWidth, window.innerHeight);
render.shadowMap.enabled = true;
document.getElementById("puiedu-webgl-output").appendChild(render.domElement);
var controls = new OrbitControls(camera, render.domElement);
controls.update();
var axes = new THREE.AxesHelper(100);
scene.add(axes);
function getTexture() {
// var texture = new THREE.TextureLoader().load("./sprite0.png")
var texture = new THREE.TextureLoader().load("./disc.png");
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function createSprites() {
for (let x = -30; x < 30; x++) {
for (let y = -30; y < 30; y++) {
for (let z = 0; z < 5; z++) {
// var material = new THREE.SpriteMaterial({
// opacity: 1,
// transparent: true,
// color: 0xffffff,
// map: getTexture()
// })
// material.map.offset = new THREE.Vector2()
// material.map.repeat = new THREE.Vector2()
// material.map.depthTest = false
var material = new THREE.PointsMaterial({ size: 35, sizeAttenuation: true, map: sprite, alphaTest: 0.5, transparent: true });
material.color.setHSL(1.0, 0.3, 0.7, THREE.SRGBColorSpace);
var sprite = new THREE.Sprite(material);
sprite.position.set(x * 4, y * 4, z * 100);
scene.add(sprite);
}
}
}
}
const geometry = new THREE.BoxGeometry(5, 5, 5);
const edges = new THREE.EdgesGeometry(geometry);
const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({ color: 0xffffff }));
var myBox = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.0,
})
);
line.name = "shiqiming";
myBox.name = "shiqiming";
line.position.set(7.5, 0, 0);
myBox.position.set(7.5, 0, 0);
scene.add(myBox);
scene.add(line);
const dir = new THREE.Vector3(0, 0, 1);
dir.normalize();
const origin = new THREE.Vector3(7.5, 0, 0);
const length = 2.5;
const hex = 0xffff00;
const arrowHelper = new THREE.ArrowHelper(dir, origin, length, hex);
scene.add(arrowHelper);
// createSprites()
// function createPoints () {
// var pGeo = new THREE.BufferGeometry()
// var pMat = new THREE.PointsMaterial({
// size: 2,
// vertexColors: true,
// color: 0xffffff,
// map: getTexture()
// })
// var positions = []
// var colors = []
// for (let x = -30; x < 30; x++) {
// for (let y = -30; y < 30; y++) {
// for (let z = -30; z < 35; z++) {
// positions.push(x * 4, y * 4, z * 100)
// // var clr = new THREE.Color(Math.random() * 0xffffff)
// var clr = new THREE.Color(0xffffff)
// colors.push(clr.r, clr.g, clr.b)
// }
// }
// }
// pGeo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3))
// pGeo.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3))
// var cloud = new THREE.Points(pGeo, pMat)
// scene.add(cloud)
// }
class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
this.pickedObject = null;
this.pickedObjectSavedColor = 0;
}
pick(normalizedPosition, scene, camera, time) {
// 恢复上一个被拾取对象的颜色
// if (this.pickedObject) {
// // this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
line.material.color.set(new THREE.Color(0xffffff));
// this.pickedObject = undefined;
// }
// 发出射线
this.raycaster.setFromCamera(normalizedPosition, camera);
// 获取与射线相交的对象
var arr = scene.children.filter((item) => {
return item.type === "Mesh";
});
const intersectedObjects = this.raycaster.intersectObjects(arr);
console.log(arr, intersectedObjects);
if (intersectedObjects.length) {
// 找到第一个对象,它是离鼠标最近的对象
// console.log(intersectedObjects)
console.log(11111);
intersectedObjects.forEach((item) => {
if (item.object.name === "shiqiming") {
// this.pickedObject = intersectedObjects[0].object;
this.pickedObject = line;
line.material.color.set(new THREE.Color(1, 0, 0));
}
});
// console.log(this.pickedObject)
// this.pickedObject.material.color.set(1, 1, 0, 1)
// 保存它的颜色
// this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
// 设置它的发光为 黄色/红色闪烁
// this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
}
}
}
{
const geometry = new THREE.BoxGeometry(3, 3, 3);
const material = new THREE.MeshPhongMaterial({
color: new THREE.Color(1, 1, 1, 1),
});
const cube = new THREE.Mesh(geometry, material);
cube.name = "qi";
scene.add(cube);
}
const pickPosition = { x: 0, y: 0 };
clearPickPosition();
function getCanvasRelativePosition(event) {
var canvas = render.domElement;
const rect = canvas.getBoundingClientRect();
return {
x: ((event.clientX - rect.left) * canvas.width) / rect.width,
y: ((event.clientY - rect.top) * canvas.height) / rect.height,
};
}
function setPickPosition(event) {
console.log("click了");
var canvas = render.domElement;
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.width) * 2 - 1;
pickPosition.y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
pickHelper.pick(pickPosition, scene, camera, new Date());
}
function clearPickPosition() {
// 对于触屏,不像鼠标总是能有一个位置坐标,
// 如果用户不在触摸屏幕,我们希望停止拾取操作。
// 因此,我们选取一个特别的值,表明什么都没选中
pickPosition.x = -100000;
pickPosition.y = -100000;
}
var isChange = false;
controls.addEventListener("change", () => {
isChange = true;
});
window.addEventListener("click", (e) => {
if (isChange) {
} else {
setPickPosition(e);
}
isChange = false;
});
// window.addEventListener('mousemove', setPickPosition);
window.addEventListener("mouseout", clearPickPosition);
window.addEventListener("mouseleave", clearPickPosition);
window.addEventListener(
"touchstart",
(event) => {
// 阻止窗口滚动行为
event.preventDefault();
setPickPosition(event.touches[0]);
},
{ passive: false }
);
window.addEventListener("touchmove", (event) => {
setPickPosition(event.touches[0]);
});
window.addEventListener("touchend", clearPickPosition);
function createPoints(arr) {
var pGeo = new THREE.BufferGeometry();
// var pMat = new THREE.PointsMaterial({
// // size: 0.02,
// // sizeAttenuation: true,
// // map: getTexture(),
// // alphaTest: 0.5,
// // transparent: true,
// size: 0.02,
// vertexColors: true,
// color: 0xffffff,
// })
const pMat = new THREE.ShaderMaterial({
uniforms: {
color: { value: new THREE.Color(0xff55ff) },
myR: { value: new THREE.Matrix4().makeRotationZ(1) },
},
vertexShader: document.getElementById("vertexshader").textContent,
fragmentShader: document.getElementById("fragmentshader").textContent,
});
var positions = [];
var colors = [];
// for (let x = -30; x < 30; x++) {
// for (let y = -30; y < 30; y++) {
// for (let z = -30; z < 35; z++) {
// positions.push(x * 4, y * 4, z * 100)
// var clr = new THREE.Color(0xffffff)
// colors.push(clr.r, clr.g, clr.b)
// }
// }
// }
// positions = arr
arr.forEach((item, index) => {
// if (index>200000) {
// return
// }
var numsArr = item.split(" ");
var x = parseFloat(numsArr[0]);
var y = parseFloat(numsArr[1]);
var z = parseFloat(numsArr[2]);
if (x && y && z) {
var clr = new THREE.Color(0xffffff);
colors.push(clr.r, clr.g, clr.b);
positions.push(x, y, z);
}
});
pGeo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
pGeo.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
var cloud = new THREE.Points(pGeo, pMat);
scene.add(cloud);
}
fetch("./0.txt")
.then((res) => {
return res.text();
})
.then((res) => {
var arr = res.split("\n");
// console.log(arr)
createPoints(arr);
});
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(0, 60, 60);
spotLight.castShadow = true;
spotLight.intensity = 0.6;
scene.add(spotLight);
// var ambientLight = new THREE.AmbientLight(0xffffff)
// scene.add(ambientLight)
var ctrl = new dat();
const pickHelper = new PickHelper();
var extrinsic = [
[-0.0040846569, 0.0016954223, 0.99999022, 0.05428632],
[-0.9999916, -0.00039857352, -0.0040839869, -0.0048804963],
[0.00039164553, -0.99999845, 0.0016970362, -0.13901815],
[0.0, 0.0, 0.0, 1.0],
];
var intrinsic = [
[1912.6069702676, 0.0, 1895.7022972943],
[0.0, 1912.2738506415, 1038.9911795727],
[0.0, 0.0, 1.0],
];
function toUVCopy(p, rt, k) {
var c = p.applyMatrix4(rt.clone().invert()).applyMatrix3(k).divideScalar(p.z);
// var res = c.applyMatrix3(k)
// res.divideScalar(res.z)
console.log(c);
}
function toUV(p, rt, k) {
let e = rt.clone().invert();
let kk = new THREE.Matrix4().setFromMatrix3(k);
kk.multiply(e);
var res = p.clone().applyMatrix4(kk);
var f = res.divideScalar(res.z);
return f;
}
let rt = new THREE.Matrix4();
rt.set(...extrinsic[0], ...extrinsic[1], ...extrinsic[2], ...extrinsic[3]);
let k = new THREE.Matrix3();
k.set(...intrinsic[0], ...intrinsic[1], ...intrinsic[2]);
var testJson = [
{
x: 55.68015780346392,
y: 8.007887796297783,
z: -0.6336926325546335,
},
{
x: 56.25721691109387,
y: 10.22232950852735,
z: -0.7051426119853355,
},
{
x: 55.88525830538232,
y: 11.528754483954556,
z: -0.76386547659488,
},
{
x: 55.81706926675467,
y: 12.240173393420244,
z: -0.8323114228981308,
},
{
x: 55.83698572614637,
y: 12.818120184616651,
z: -0.8971045922480612,
},
{
x: 56.08459957428591,
y: 13.460489666163621,
z: -0.9870512389391799,
},
{
x: 56.47043176187681,
y: 13.769558426098477,
z: -0.9998380016185171,
},
{
x: 57.03548129045228,
y: 14.135034296872144,
z: -0.9196784422767739,
},
{
x: 64.12790448594512,
y: 16.50903400854992,
z: -0.8169057384777145,
},
{
x: 70.49803499937642,
y: 18.530356548102052,
z: -0.6980516197806383,
},
{
x: 82.49584633903744,
y: 22.418233951035454,
z: -0.493139408172901,
},
{
x: 94.19968288138567,
y: 26.14772098523855,
z: -0.35307277906111073,
},
{
x: 94.19968288138567,
y: 26.14772098523855,
z: -0.35307277906111073,
},
];
testJson.forEach(item => {
var p = new THREE.Vector3(item.x, item.y, item.z);
var res = toUV(p, rt, k);
console.log(res);
})
function renderScene(time) {
stats.update();
controls.update();
// pickHelper.pick(pickPosition, scene, camera, time)
requestAnimationFrame(renderScene);
render.render(scene, camera);
}
renderScene();
window.addEventListener("resize", onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
render.setSize(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guohuacai/threejs.git
git@gitee.com:guohuacai/threejs.git
guohuacai
threejs
threejs
master

Search