<%@ Page Language="C#" ContentType="text/html; charset=utf-8" ResponseEncoding="utf-8" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>3D 水泵模型展示</title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
body {
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
text-align: center;
margin-bottom: 30px;
}
#canvas-container {
width: 100%;
height: 600px;
border: 2px solid #ddd;
border-radius: 5px;
margin-bottom: 20px;
background-color: #fff;
overflow: hidden;
}
.button-group {
text-align: center;
margin-bottom: 20px;
}
.btn {
margin: 0 10px;
padding: 10px 20px;
font-size: 16px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Name="MicrosoftAjax.js" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.js" />
</Scripts>
</asp:ScriptManager>
<div class="container">
<h1>3D 水泵模型展示</h1>
<div class="button-group">
<button type="button" id="startBtn" class="btn btn-success">启动</button>
<button type="button" id="stopBtn" class="btn btn-danger">停止</button>
<button type="button" id="testBtn" class="btn btn-info">测试写入</button>
</div>
<div id="canvas-container">
<canvas id="myCanvas"></canvas>
</div>
</div>
</form>
<!-- Include jQuery library -->
<script src="Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
// 检查jQuery是否加载成功
if (typeof jQuery !== 'undefined') {
console.log('jQuery已成功加载');
} else {
console.error('jQuery未加载成功');
}
</script>
<!-- Include Three.js library and components as ES modules -->
<script type="module">
// Import Three.js modules
import * as THREE from '/Scripts/threejs/three.module.js';
import { GLTFLoader } from '/Scripts/threejs/GLTFLoader.js';
import { OrbitControls } from '/Scripts/threejs/OrbitControls.js';
// Initialize Three.js scene
var scene, camera, renderer, controls;
window.pumpModel = null; // 暴露给全局以便传统脚本访问
window.pumpModelColor = 0xff0000; // Default red color
function init() {
console.log('Initializing Three.js scene');
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff); // White background for better contrast
// Create camera
camera = new THREE.PerspectiveCamera(60, document.getElementById('canvas-container').clientWidth / document.getElementById('canvas-container').clientHeight, 0.1, 1000);
camera.position.set(5, 5, 5); // Move camera further away and at an angle
// Create renderer
renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('myCanvas'), antialias: true });
renderer.setSize(document.getElementById('canvas-container').clientWidth, document.getElementById('canvas-container').clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
// Add orbit controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Add lights
var ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
var directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight2.position.set(-1, -1, -1);
scene.add(directionalLight2);
// Add a visible grid to help with orientation
var gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);
// Add axes helper
var axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// Add a simple sphere to verify Three.js is working
var sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
var sphereMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(0, 0, 0);
scene.add(sphere);
console.log('Sphere added to scene');
// Load 3D model
console.log('Starting to load model...');
var loader = new GLTFLoader();
// First, check if the model file exists
fetch('/3D/shuibneg.glb')
.then(response => {
if (response.ok) {
console.log('Model file exists, starting to load...');
loader.load('/3D/shuibneg.glb',
function (gltf) {
console.log('Model loaded successfully!');
window.pumpModel = gltf.scene;
// Remove the sphere
scene.remove(sphere);
// Adjust model size and position
console.log('Original model bounding box:', new THREE.Box3().setFromObject(window.pumpModel).getSize(new THREE.Vector3()));
// Center the model
const box = new THREE.Box3().setFromObject(window.pumpModel);
const center = box.getCenter(new THREE.Vector3());
window.pumpModel.position.sub(center);
// Scale model to fit in view
const size = box.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180);
let cameraZ = Math.abs(maxDim / 2 / Math.tan(fov / 2));
cameraZ *= 1.5; // Add a little extra space
camera.position.set(0, 0, cameraZ);
// Look at model
const minZ = box.min.z;
const cameraToFarEdge = (minZ < 0) ? -minZ + cameraZ : cameraZ - minZ;
camera.far = cameraToFarEdge * 3;
camera.updateProjectionMatrix();
// Apply initial color
applyColor(window.pumpModel, window.pumpModelColor);
scene.add(window.pumpModel);
console.log('Model added to scene');
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.error('Error loading model:', error);
console.error('Error details:', error.message, error.stack);
}
);
} else {
console.error('Model file not found:', response.status);
}
})
.catch(error => {
console.error('Error checking model file:', error);
});
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
// Start animation loop
animate();
}
function onWindowResize() {
camera.aspect = document.getElementById('canvas-container').clientWidth / document.getElementById('canvas-container').clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(document.getElementById('canvas-container').clientWidth, document.getElementById('canvas-container').clientHeight);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
// Apply color to all materials of the model
function applyColor(object, color) {
object.traverse(function (child) {
if (child.isMesh) {
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(function (material) {
material.color.setHex(color);
});
} else {
child.material.color.setHex(color);
}
}
}
});
}
// Initialize when all resources are loaded
window.addEventListener('load', init);
</script>
<!-- Traditional script for PageMethods calls -->
<script type="text/javascript">
// 定时器ID,用于控制定时写入
let writeTimer = null;
// 页面加载完成后检查PageMethods是否可用
window.addEventListener('load', function() {
console.log('页面加载完成,检查PageMethods:', typeof PageMethods);
if (typeof PageMethods !== 'undefined') {
console.log('PageMethods可用');
} else {
console.error('PageMethods不可用');
}
});
// 使用jQuery AJAX调用WebMethod(备用方案)
function writeToEliveAjax() {
console.log('使用AJAX调用writeToElive');
// 获取__VIEWSTATE和__EVENTVALIDATION值(用于CSRF保护)
const viewState = document.getElementById('__VIEWSTATE') ? document.getElementById('__VIEWSTATE').value : '';
const eventValidation = document.getElementById('__EVENTVALIDATION') ? document.getElementById('__EVENTVALIDATION').value : '';
// 准备请求数据
const data = JSON.stringify({});
$.ajax({
type: 'POST',
url: 'Q4_3D.aspx/WriteToElive',
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
beforeSend: function(xhr) {
// 添加CSRF令牌
xhr.setRequestHeader('__VIEWSTATE', viewState);
xhr.setRequestHeader('__EVENTVALIDATION', eventValidation);
},
success: function(response) {
console.log('AJAX请求成功:', response);
if (response.d) {
onSuccess(response.d);
} else {
console.error('AJAX请求返回失败结果');
}
},
error: function(xhr, status, error) {
console.error('AJAX请求失败:', error);
console.log('状态:', status);
console.log('响应:', xhr.responseText);
onError({ get_message: function() { return error; } });
}
});
}
// 调用Web方法写入数据
function writeToElive() {
console.log('调用writeToElive函数');
if (typeof PageMethods !== 'undefined') {
console.log('准备调用PageMethods.WriteToElive');
PageMethods.WriteToElive(onSuccess, onError);
} else {
console.error('PageMethods未定义,尝试使用AJAX调用');
writeToEliveAjax();
}
}
// 成功回调函数
function onSuccess(result) {
console.log('写入数据库结果:', result);
}
// 错误回调函数
function onError(error) {
console.error('写入数据库时出错:', error.get_message());
}
// Start button click event
document.getElementById('startBtn').addEventListener('click', function () {
window.pumpModelColor = 0x00ff00; // Green color
if (window.pumpModel) {
// 通过调用模块中的applyColor函数修改颜色
const model = window.pumpModel;
const color = window.pumpModelColor;
model.traverse(function (child) {
if (child.isMesh) {
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(function (material) {
material.color.setHex(color);
});
} else {
child.material.color.setHex(color);
}
}
}
});
}
// 存储状态到localStorage,以便其他页面获取
localStorage.setItem('pumpStatus', 'running');
// 触发自定义事件,通知其他监听者
window.dispatchEvent(new Event('storage'));
// 每2秒写入一次数据库
if (writeTimer === null) {
writeTimer = setInterval(writeToElive, 2000);
}
});
// Test button click event
document.getElementById('testBtn').addEventListener('click', function () {
console.log('点击了测试按钮');
writeToElive();
});
// Stop button click event
document.getElementById('stopBtn').addEventListener('click', function () {
window.pumpModelColor = 0xff0000; // Red color
if (window.pumpModel) {
// 通过调用模块中的applyColor函数修改颜色
const model = window.pumpModel;
const color = window.pumpModelColor;
model.traverse(function (child) {
if (child.isMesh) {
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(function (material) {
material.color.setHex(color);
});
} else {
child.material.color.setHex(color);
}
}
}
});
}
// 存储状态到localStorage,以便其他页面获取
localStorage.setItem('pumpStatus', 'stopped');
// 触发自定义事件,通知其他监听者
window.dispatchEvent(new Event('storage'));
// 停止定时器
if (writeTimer !== null) {
clearInterval(writeTimer);
writeTimer = null;
}
});
</script>
</body>
</html>如何实现按下启动按钮向数据库写入信息
最新发布