-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs4143engine0.html
More file actions
executable file
·667 lines (560 loc) · 20.3 KB
/
Copy pathcs4143engine0.html
File metadata and controls
executable file
·667 lines (560 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
<!DOCTYPE html>
<html lang="en">
<!--
=============================================================================
CS 4143 GAME ENGINE BASE
Author: David Cline
=============================================================================
Description:
For use by students in CS 4143 at Oklahoma State University, Fall 2016.
Provides basic code for:
- loading several object types
- a game loop
- keyboard and mouse input
- scripting
Running a scene:
Scene files are written in JSON, and must be specified as part of the
URL when loading the engine. If scene0a.json is the relative URL of the
scene, then the engine should be started with:
.../cs4143engine0.html?url=scene0a.json
SimpleHTTPServer:
Python provides a simple http server that can be used to test files
on the local machine (since the file server will likely not work.
From the directory that you want to be the root of localhost,
run python with the command:
python -m SimpleHTTPServer
It should respond with
Serving HTTP on 0.0.0.0 port 8000 ...
At this point, in your browser, you should be able to access files
using the URL
http://localhost:8000/
=============================================================================
-->
<!-- HTML HEAD TAG -->
<head>
<title>CS 4143 Game Engine Base by David Cline</title>
<meta charset="utf-8">
<!-- CSS THAT DEFINES THE STYLE IN WHICH HTML ELEMENTS WILL BE RENDERED -->
<style>
body {
font-family: sans-serif; /* Tells what font to use by default */
background-color: #000; /* Black background */
color: #fff; /* White foreground */
margin: 0px; /* How much space to draw around everything */
overflow: hidden; /* Hides the scroll bar */
}
#left {
color: #fff; /* White foreground for these #info elements */
/* Unspecified background is transparent */
opacity: 0.8; /* opacity of element */
position: absolute; /* #info elements do not flow with document */
left: 5px; /* left margin */
top: 5px; /* left margin */
text-align: left; /* Text alignment */
z-index: 100; /* High draw order (drawn on top) */
display:block; /* Display elements should be stacked vertically */
}
</style>
</head>
<!-- ==================================================================== -->
<!-- HTML BODY TAG - TURNS OFF RIGHT CLICK -->
<body oncontextmenu="return false;">
<!-- DEFINE LEFT DIV TAG - FOR DEBUG PRINTOUTS -->
<div id="left">
<pre id="debug"></pre>
</div>
<!-- INCLUDE SCRIPTS HERE -->
<script src="../threejs/build/three.js"></script>
<!-- ==================================================================== -->
<!-- THE ACTUAL JAVASCRIPT ENGINE CODE -->
<!-- ==================================================================== -->
<script>
//----------------------------------------------------------------------//
// GLOBAL VARIABLES
//----------------------------------------------------------------------//
// GENERAL CONSTANTS
var XAXIS = new THREE.Vector3(1,0,0);
var YAXIS = new THREE.Vector3(0,1,0);
var ZAXIS = new THREE.Vector3(0,0,1);
var DEBUG = true; // Whether to run in debug mode
var startTime = 0; // When the scene was loaded (in seconds)
var sceneURL; // URL of the scene to be loaded
var rendererContainer; // A div element that will hold the renderer
var loadingManager; // loading manager
// MOUSE DATA
var mouseX = 0; // Current position of mouse
var mouseY = 0;
var mousePrevX = 0; // Previous position of mouse
var mousePrevY = 0;
var mouseDown = 0; // Which mouse button currently down
var mouseScroll = 0; // How much the mouse wheel has scrolled
var mousePrevScroll = 0;
// KEYBOARD DATA
var pressedKeys = {}; // Which keys are currently depressed on the keyboard
// WINDOW SIZE
var windowWidth = 100; // Current width and height of the window
var windowHeight = 100;
// SCENE SPECIFIC DATA
var currentScene; // The current scene graph
var currentCamera; // The current camera used to render the scene
var currentRenderer; // The current renderer used to render the scene
// INITIALIZATION AND STARTUP (EXECUTES WHEN PAGE LOADS)
processArgs();
init();
loadScene(sceneURL);
animate();
//----------------------------------------------------------------------//
// PROCESSES THE URL ARGUMENTS, WHICH SHOULD CONTAIN THE SCENE URL
//----------------------------------------------------------------------//
function processArgs()
{
var href = window.location.href;
var args = href.slice(href.indexOf('?') + 1).split('&');
for(var i = 0; i < args.length; i++) {
var arg = args[i].split('=');
if (arg[0] == 'url') {
sceneURL = arg[1];
}
else if (arg[0] == 'debug') {
if (arg[1] == 'true') DEBUG = true;
else DEBUG = false;
}
}
if (sceneURL === undefined) {
sceneURL = "scene0a.json"
DEBUG = true;
debug("No scene specified\n");
debug("Use: .../cs4143engine0.html?url=sceneURL\n");
}
}
//----------------------------------------------------------------------//
// PERFORM GENERAL INITIALIZATION. CREATE THE RENDERER AND LOADING
// MANAGER, AND START LISTENING TO GUI EVENTS.
//----------------------------------------------------------------------//
function init()
{
debug("init\n");
// Create a container to hold the renderer and add it to the page
rendererContainer = document.createElement( 'div' );
document.body.appendChild( rendererContainer );
// Make the loading manager for Three.js.
loadingManager = new THREE.LoadingManager();
loadingManager.onProgress = function ( item, loaded, total ) {
// do nothing
};
// Create renderer and add it to the container (div element)
var renderer = new THREE.WebGLRenderer( {antialias:true} );
renderer.setPixelRatio( window.devicePixelRatio );
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
renderer.setSize( windowWidth, windowHeight );
rendererContainer.appendChild( renderer.domElement );
currentRenderer = renderer;
// Add event listeners so we can respond to events
window.addEventListener( 'resize', onWindowResize, false );
//
document.addEventListener( 'mouseup', onMouseUp, false );
document.addEventListener( 'mousedown', onMouseDown, false );
document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'mousewheel', onMouseWheel, false);
document.addEventListener( 'DOMMouseScroll', onMouseWheel, false); // firefox
//
window.onkeydown = onKeyDown;
window.onkeyup = onKeyUp;
}
//------------------------------------------------------------------//
// EVENT LISTENERS
//------------------------------------------------------------------//
function onWindowResize(event)
{
//debug("onWindowResize\n");
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
currentCamera.aspect = windowWidth / windowHeight;
currentCamera.updateProjectionMatrix();
currentRenderer.setSize( windowWidth, windowHeight );
}
//------------------------------------------------------------------//
function onMouseUp(event)
{
//debug("onMouseUp\n");
mouseDown = 0;
}
function onMouseDown(event)
{
//debug("onMouseDown " + event.which + "\n");
mouseDown = event.which;
}
function onMouseMove(event)
{
//debug("onMouseMove " + event.clientX + "," + event.clientY + "\n");
//mousePrevX = mouseX; // don't do this yet because asynchronous
//mousePrevY = mouseY;
mouseX = event.clientX;
mouseY = event.clientY;
}
function onMouseWheel(event)
{
if (event.detail > 0 || event.detail < 0) {
mouseScroll += event.detail/120.0;
}
if (event.wheelDelta > 0 || event.wheelDelta < 0) {
mouseScroll += event.wheelDelta/120.0;
}
//debug("onMouseWheel " + mouseScroll + "\n");
}
//------------------------------------------------------------------//
function onKeyDown(event)
{
var key = event.keyCode ? event.keyCode : event.which;
pressedKeys[key] = true;
debug("onKeyDown " + key + "\n");
}
function onKeyUp(event)
{
var key = event.keyCode ? event.keyCode : event.which;
delete pressedKeys[key];
//debug("onKeyDown " + key + "\n");
}
//----------------------------------------------------------------------//
// PRINT A DEBUG MESSAGE
//----------------------------------------------------------------------//
function debug(message)
{
if (DEBUG)
{
var element = document.getElementById("debug");
element.innerHTML += message;
}
console.log(message);
}
//----------------------------------------------------------------------//
// GET THE ELAPSED TIME (SINCE THE PAGE LOADED) IN SECONDS
//----------------------------------------------------------------------//
function getElapsedTime()
{
var d = new Date();
var t = d.getTime() * 0.001 - startTime;
return t;
}
//----------------------------------------------------------------------//
// LOAD A SCENE (ASYNCHRONOUSLY)
// THE SCENE IS LOADED FROM THE SPECIFIED URL AS A STRING, AND THEN
// PARSED AS A JSON OBJECT. AT THAT POINT parseScene IS CALLED ON
// IT, WHICH RECURSIVELY WALKS THE parseTree CREATING A Three.js scene.
//----------------------------------------------------------------------//
function loadScene(sceneURL)
{
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", sceneURL, true);
httpRequest.send(null);
httpRequest.onload =
function() {
debug("loading " + sceneURL + " ...\n");
var jsonParseTree = JSON.parse(httpRequest.responseText);
debug("parsing\n");
parseScene(jsonParseTree);
debug("done.\n");
}
}
//----------------------------------------------------------------------//
// ENTRY POINT TO RECURSIVE FUNCTION THAT TRAVERSES THE JSON PARSE
// TREE AND MAKES A SCENE.
//----------------------------------------------------------------------//
function parseScene(jsonParseTree)
{
debug("parseScene\n");
var scene = new THREE.Scene();
parseSceneNode(jsonParseTree, scene);
startTime = (new Date()).getTime() * 0.001; // reset start time
currentScene = scene;
}
//----------------------------------------------------------------------//
// THE MAIN RECURSIVE FUNCTION OF THE PARSER.
// THE JOB OF parseSceneNode IS TO TRAVERSE THE JSON OBJECT jsonNode
// AND POPULATE A CORRESPONDING Three.js SceneNode
//----------------------------------------------------------------------//
function parseSceneNode(jsonNode, sceneNode)
{
debug("parseSceneNode " + jsonNode["name"] + ":" + jsonNode["type"] + "\n");
if (jsonNode === undefined || sceneNode === undefined) return;
// Handle the transform of the node (translation, rotation, etc.)
parseTransform(jsonNode, sceneNode);
// Load any script files (note that these are not scripts attached
// to the current node, just files that contain code.)
if ("scriptFiles" in jsonNode) {
var scriptList = jsonNode["scriptFiles"];
for (var i=0; i<scriptList.length; i++) {
var scriptURL = scriptList[i];
loadScript(scriptURL);
}
}
// User data that will be placed in the node. Can be arbitrary.
// Includes the names of any scripts attached to the node.
if ("userData" in jsonNode) {
sceneNode["userData"] = jsonNode["userData"];
} else {
sceneNode["userData"] = {};
}
// Load and play background music
if ("backgroundMusic" in jsonNode) {
var audio = new Audio(jsonNode["backgroundMusic"]);
debug("playing " + jsonNode["backgroundMusic"] + "\n");
audio.play();
}
// The name of the node (useful to look up later in a script)
if ("name" in jsonNode) {
sceneNode["name"] = jsonNode["name"];
}
// Whether the node starts out as visible.
if ("visible" in jsonNode) {
sceneNode.setVisible(jsonNode["visible"]);
}
// Traverse all the child nodes. The typical code pattern here is:
// 1. call a special routine that creates the child based on its type.
// This routine also deals with attributes specific to that node type.
// 2. Make a recursive call to parseSceneNode, which handles general
// properties that any node can include.
if ("children" in jsonNode)
{
var children = jsonNode["children"];
for (var i=0; i<children.length; i++)
{
var childJsonNode = children[i];
var childType = childJsonNode["type"];
if (childType == "node") { // empty object to hold a transform
var childSceneNode = new THREE.Object3D();
sceneNode.add(childSceneNode);
parseSceneNode(childJsonNode, childSceneNode);
}
if (childType == "perspectiveCamera") {
var camera = parsePerspectiveCamera(childJsonNode);
sceneNode.add(camera);
if (currentCamera === undefined) currentCamera = camera;
parseSceneNode(childJsonNode, camera);
}
else if (childType == "directionalLight") {
var light = parseDirectionalLight(childJsonNode);
sceneNode.add(light);
parseSceneNode(childJsonNode, light);
}
else if (childType == "mesh") {
var mesh = parseMesh(childJsonNode);
sceneNode.add(mesh);
parseSceneNode(childJsonNode, mesh);
}
}
}
}
//----------------------------------------------------------------------//
// PARSE A TRANSFORM
//----------------------------------------------------------------------//
function parseTransform(jsonNode, sceneNode)
{
//debug("parseTransform\n");
if ("translate" in jsonNode) {
var translate = jsonNode["translate"];
sceneNode.position.x += translate[0];
sceneNode.position.y += translate[1];
sceneNode.position.z += translate[2];
}
if ("scale" in jsonNode) {
var scale = jsonNode["scale"];
sceneNode.scale.x *= scale[0];
sceneNode.scale.y *= scale[1];
sceneNode.scale.z *= scale[2];
}
if ("rotate" in jsonNode) {
var rotate = jsonNode["rotate"];
var axis = new THREE.Vector3(rotate[0], rotate[1], rotate[2]);
var radians = rotate[3];
sceneNode.rotateOnAxis(axis, radians);
}
}
//----------------------------------------------------------------------//
// PARSE A PERSPECTIVE CAMERA
//----------------------------------------------------------------------//
function parsePerspectiveCamera(jsonNode)
{
//debug("parsePerspectiveCamera\n");
// Start with default values
var near = 0.2;
var far = 10000.0;
var aspect = windowWidth / windowHeight;
var fovy = 60.0;
var eye = [0.0, 0.0, 100.0];
var vup = [0.0, 1.0, 0.0];
var center = [0.0, 0.0, 0.0];
// Replace with data from jsonNode
if ("near" in jsonNode) near = jsonNode["near"];
if ("far" in jsonNode) far = jsonNode["far"];
if ("fov" in jsonNode) fovy = jsonNode["fov"];
if ("eye" in jsonNode) eye = jsonNode["eye"];
if ("vup" in jsonNode) vup = jsonNode["vup"];
if ("center" in jsonNode) center = jsonNode["center"];
// Create and return the camera
var camera = new THREE.PerspectiveCamera( fovy, aspect, near, far );
camera.position.set( eye[0], eye[1], eye[2] );
camera.up.set( vup[0], vup[1], vup[2] );
camera.lookAt( new THREE.Vector3(center[0], center[1], center[2]) );
return camera;
}
//----------------------------------------------------------------------//
// PARSE A DIRECTIONAL LIGHT
//----------------------------------------------------------------------//
function parseDirectionalLight(jsonNode)
{
//debug("parseDirectionalLight\n");
// Start with default values
var color = [1.0, 1.0, 1.0];
var position = [1.0, 1.0, 1.0];
// Replace with data from jsonNode
if ("color" in jsonNode) color = jsonNode["color"];
if ("position" in jsonNode) position = jsonNode["position"];
// Create the light and return it
var c = new THREE.Color(color[0], color[1], color[2]);
var light = new THREE.DirectionalLight( c );
light.position.set( position[0], position[1], position[2] );
return light;
}
//----------------------------------------------------------------------//
// PARSE A MESH
//----------------------------------------------------------------------//
function parseMesh(jsonNode)
{
//debug("parseMesh\n");
// Get the material
var material = parseMaterial(jsonNode["material"]);
// Create the mesh geometry
var geometryType = jsonNode["geometry"];
var geometry;
if (geometryType == "cube") {
var width = 2;
var height = 2;
var depth = 2;
if ("width" in jsonNode) width = jsonNode["width"];
if ("height" in jsonNode) height = jsonNode["height"];
if ("depth" in jsonNode) depth = jsonNode["depth"];
geometry = new THREE.BoxGeometry(width, height, depth);
}
else if (geometryType == "sphere") {
var radius = 1;
var widthSegments = 8;
var heightSegments = 6;
if ("radius" in jsonNode) radius = jsonNode["radius"];
if ("widthSegments" in jsonNode) widthSegments = jsonNode["widthSegments"];
if ("heightSegments" in jsonNode) heightSegments = jsonNode["heightSegments"];
geometry = new THREE.SphereGeometry(radius, heightSegments, widthSegments);
}
// Create the mesh and return it
var mesh = new THREE.Mesh( geometry, material );
return mesh;
}
//----------------------------------------------------------------------//
// PARSE A MATERIAL
//----------------------------------------------------------------------//
function parseMaterial(jsonNode)
{
//debug("parseMaterial\n");
if (jsonNode === undefined) return new MeshLambertMaterial();
var type = jsonNode["type"];
// Lambertian material
if (type == "meshLambertMaterial")
{
var material = new THREE.MeshLambertMaterial();
if ("diffuseColor" in jsonNode) {
var d = jsonNode["diffuseColor"];
material.color = new THREE.Color(d[0], d[1], d[2]);
}
if ("diffuseMap" in jsonNode) {
var tex = parseTexture( jsonNode["diffuseMap"] );
material.map = tex;
}
return material;
}
// Failed to make a material, so return a default
return new MeshLambertMaterial();
}
//----------------------------------------------------------------------//
// PARSE A TEXTURE MAP - ASYNCHRONOUSLY LOADS THE TEXTURE IMAGE
//----------------------------------------------------------------------//
function parseTexture(textureURL)
{
//debug("parseTexture: " + textureURL + "\n");
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader(manager);
loader.load(
textureURL,
function(image) { // callback function
texture.image = image;
texture.needsUpdate = true;
}
);
return texture;
}
//----------------------------------------------------------------------//
// ADD A SCRIPT TO THE RUNNING PAGE FROM AN EXTERNAL URL
//----------------------------------------------------------------------//
function loadScript(scriptURL)
{
//debug("loadScript " + scriptURL + "\n");
// Create an element for the script
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptURL;
// Add the script element to the head of the page
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
//----------------------------------------------------------------------//
// THE MAIN FUNCTION OF THE GAME (ANIMATION) LOOP
//----------------------------------------------------------------------//
function animate()
{
requestAnimationFrame(animate); // schedules another call to animate
animateFrame(); // updates the scene for the frame
render(); // draws the scene
}
//----------------------------------------------------------------------//
// CONTROLS ANIMATING A SINGLE FRAME
//----------------------------------------------------------------------//
function animateFrame()
{
// Update the current camera and scene
if (currentCamera !== undefined) currentCamera.updateProjectionMatrix();
if (currentScene !== undefined) currentScene.traverse(runScripts);
// Update previous mouse state here because animateFrame
// out of sync with mouse listeners (onMouseMove, onMouseWheel)
mousePrevX = mouseX;
mousePrevY = mouseY;
mousePrevScroll = mouseScroll;
}
//----------------------------------------------------------------------//
// CALLBACK TO RUN ALL THE SCRIPTS FOR A GIVEN sceneNode
//----------------------------------------------------------------------//
function runScripts(sceneNode)
{
var scripts = sceneNode.userData.scripts;
if (scripts === undefined) return;
for (var j=0; j<scripts.length; j++) {
var s = scripts[j];
var f = window[s]; // look up function by name
if (f !== undefined) f(sceneNode);
}
}
//----------------------------------------------------------------------//
// RENDER CURRENT SCENE WITH CURRENT RENDERER USING CURRENT CAMERA
//----------------------------------------------------------------------//
function render()
{
if (currentScene && currentCamera && currentRenderer) {
currentRenderer.render(currentScene, currentCamera);
}
else {
//debug("Problem rendering\n");
}
}
//----------------------------------------------------------------------//
</script>
</body>
</html>