app.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // nikatlas -- Solar System
  2. (function() {
  3. var MAX_CAM = 300;
  4. PouchDB.debug.disable('*');
  5. var ZEROVECTOR = new THREE.Vector2(0,0);
  6. var X_AXIS = new THREE.Vector3(1,0,0);
  7. var Y_AXIS = new THREE.Vector3(0,1,0);
  8. var Z_AXIS = new THREE.Vector3(0,0,1);
  9. var ZERO_ROT_QUAT = new THREE.Quaternion(0,0,0,1);
  10. var controls;
  11. var manager;
  12. var loader;
  13. var _textures = {};
  14. var Game = window.GameInstance = new window.Game();
  15. var GameBox = new window.GameBox(5,14,5);
  16. var moveVector = new THREE.Vector2(0,0);
  17. var lookVector = new THREE.Vector3(0,0,1);
  18. var paused = false;
  19. var db = new PouchDB('tetris3d');
  20. window.remoteDB = new PouchDB('http://tetrisuser:[email protected]:80/tetris3d');
  21. function init() {
  22. Game.init();
  23. addLights(Game.scene);
  24. window.scene = Game.scene; // DEBUG
  25. manager = new THREE.LoadingManager();
  26. loader = new THREE.TextureLoader(manager);
  27. createScene(Game.scene);
  28. // controls
  29. controls = new THREE.OrbitControls(Game.camera, Game.renderer.domElement);
  30. controls.minPolarAngle = Math.PI * 0.28;
  31. controls.maxPolarAngle = Math.PI * 0.48;
  32. controls.minDistance = 30;
  33. controls.maxDistance = MAX_CAM;
  34. controls.target.copy(new THREE.Vector3(0,5.5,0));
  35. Game.camera.lookAt(new THREE.Vector3(0,5.5,0));
  36. GameBox.init(Game.scene);
  37. GameBox.drop(new window.Shapes.Box(0x00ff20));
  38. Game.animate();
  39. var lasttime = 0,movelasttime=0;
  40. var oldLookVector = new THREE.Vector3(0,0,1);
  41. Game.addLoopFn(function(time){
  42. if(time - lasttime > GameBox.getSpeed() && !paused ){ //////////////////////////////////////////////// TIME .....
  43. GameBox.progress();
  44. lasttime = time;
  45. }
  46. if(time - movelasttime > 0.05){
  47. if(!moveVector.equals(ZEROVECTOR) || !lookVector.equals(oldLookVector)){
  48. var move = rotateToCamera(moveVector);
  49. var look = rotateToCamera(lookVector);
  50. look = vectorToLook(look);
  51. GameBox.move(move.x,move.z, look.axis, look.degrees);
  52. oldLookVector.copy(lookVector);
  53. movelasttime = time;
  54. }
  55. }
  56. restoreUI();
  57. });
  58. function fixData(){
  59. db.allDocs({
  60. include_docs: true,
  61. descending : true,
  62. limit : 5
  63. }).then(function(res){
  64. var data = res.rows;
  65. var s = "";
  66. for(var i=0;i< data.length;i++){
  67. s += ' \
  68. <div class="row">\
  69. <div class="col-xs-6">'+data[i].doc.name+'</div>\
  70. <div class="col-xs-6">'+data[i].doc.score+'</div>\
  71. </div>';
  72. }
  73. var scores = getit("scores");
  74. scores.innerHTML = s;
  75. });
  76. }
  77. window.getFromDB = function(){
  78. db.changes().on('change', function() {
  79. fixData();
  80. });
  81. remoteDB.login('nikatlas', 'Nikos0349').then(function (user) {
  82. db.info();
  83. })
  84. .then(function (info) {
  85. console.log(info);
  86. db.sync(remoteDB);
  87. });
  88. };
  89. getFromDB();
  90. window.saveToDB = function(){
  91. var name = getit("name").value;
  92. if(!name)return;
  93. var mid = pad(GameBox.score,100) + name;
  94. db.put({
  95. _id : mid,
  96. name : name,
  97. score : GameBox.score
  98. }).then(function (result) {
  99. console.log(result);
  100. fixData();
  101. }).catch(function (err) {
  102. console.log(err);
  103. });;
  104. };
  105. }
  106. function pad(num, size) {var s = num+"";while (s.length < size) s = "0" + s;return s;}
  107. function getit(id){return document.getElementById(id);};
  108. function restoreUI(){
  109. var score = getit("highscore");
  110. score.innerHTML = GameBox.score || 0;
  111. if(GameBox.finished){
  112. var lost = getit("lost");
  113. lost.style.display = "block";
  114. var mscore = getit("myscore");
  115. mscore.innerHTML = GameBox.score || 0;
  116. }
  117. };
  118. window.restartGame = function(){
  119. if(GameBox.finished){
  120. var lost = getit("lost");
  121. lost.style.display = "none";
  122. GameBox.restart();
  123. }
  124. }
  125. function rotateToCamera(v){
  126. var mat4 = new THREE.Matrix4();
  127. mat4.makeRotationFromQuaternion(Game.camera);
  128. var rot;
  129. if(v.z == undefined){
  130. rot = new THREE.Vector3(v.x,0,v.y);
  131. }
  132. else{
  133. rot = new THREE.Vector3(v.x,v.y,v.z);
  134. }
  135. rot.applyQuaternion(Game.camera.getWorldQuaternion());
  136. var x = rot.x;
  137. var y = rot.y;
  138. var z = rot.z;
  139. var ax = Math.abs(x) > Math.abs(z) && Math.abs(x) > Math.abs(y);
  140. var ay = Math.abs(y) > Math.abs(x) && Math.abs(y) > Math.abs(z);
  141. var az = Math.abs(z) > Math.abs(x) && Math.abs(z) > Math.abs(y);
  142. var sx = x > 0 ? 1 : -1;
  143. var sy = y > 0 ? 1 : -1;
  144. var sz = z > 0 ? 1 : -1;
  145. rot.set(sx * ax, sy * ay,sz * az);
  146. return rot;
  147. }
  148. function getRotationOf(u, v)
  149. {
  150. if( u.equals(v) )return ZERO_ROT_QUAT;
  151. // It is important that the inputs are of equal length when
  152. // calculating the half-way vector.
  153. u = u.clone().normalize();
  154. v = v.clone().normalize();
  155. var k_cos_theta = u.clone().dot(v);
  156. var k = Math.sqrt(u.length() * v.length());
  157. // Unfortunately, we have to check for when u == -v, as u + v
  158. // in this case will be (0, 0, 0), which cannot be normalized.
  159. // if (u.equals(v.clone().multiplyScalar(-1)))
  160. if (k_cos_theta / k == -1)
  161. {
  162. // 180 degree rotation around any orthogonal vector
  163. var orthv = Y_AXIS;
  164. orthv.normalize();
  165. return new THREE.Quaternion(orthv.x , orthv.y , orthv.z , 0);
  166. }
  167. var cross = u.cross(v);
  168. return new THREE.Quaternion(cross.x , cross.y , cross.z , k_cos_theta + k ).normalize();
  169. }
  170. function vectorToLook(v){
  171. var q = getRotationOf(Z_AXIS, v);
  172. var qw = q.w;
  173. var angle = 2 * Math.acos(qw)
  174. var x = q.x / Math.sqrt(1-qw*qw)
  175. var y = q.y / Math.sqrt(1-qw*qw)
  176. var z = q.z / Math.sqrt(1-qw*qw)
  177. var look = {
  178. axis : new THREE.Vector3(x,y,z),
  179. degrees : angle
  180. };
  181. return look;
  182. }
  183. // Create Scene
  184. function createScene(scene){
  185. box = createBox(5,5,5,0x11ff20);
  186. box.receiveShadow = true;
  187. box.castShadow = true;
  188. box.position.copy(new THREE.Vector3( -4 , 7 , 4 ));
  189. //console.log(box.position);
  190. //scene.add(box);
  191. box = createBox(4,1,4,0x00ff20);
  192. box.receiveShadow = true;
  193. box.castShadow = true;
  194. box.position.copy(new THREE.Vector3( 1 , 4 , 0 ));
  195. //console.log(box.position);
  196. //scene.add(box);
  197. plane = createTerrain(2025,2025,0x7f8f6f);
  198. plane.rotation.x = Math.PI / 2;
  199. plane.receiveShadow = true;
  200. scene.add(plane);
  201. target = scene;
  202. createSkybox(scene);
  203. }
  204. // Lights
  205. function createDLight(color, intensity) {
  206. var l = new THREE.DirectionalLight( color, intensity );
  207. l.castShadow = true;
  208. l.shadowCameraRight = 30;
  209. l.shadowCameraLeft = -30;
  210. l.shadowCameraTop = 30;
  211. l.shadowCameraBottom = -30;
  212. l.shadow.mapSize.width = 1024;
  213. l.shadow.mapSize.height = 1024;
  214. l.shadow.map = null;
  215. return l;
  216. }
  217. function addLights(scene) {
  218. scene.add(new THREE.AmbientLight(0x111111)); // Ambient light
  219. // White directional light at half intensity shining from the top.
  220. var directionalLight = createDLight( 0xffffff, 0.55 );
  221. directionalLight.position.copy(new THREE.Vector3( 0 , 50, 0));
  222. directionalLight.castShadow = true;
  223. // var directionalLight2 = createDLight( 0xffffff, 0.15 );
  224. // directionalLight2.position.copy(new THREE.Vector3( -100 , 100, -45 ));
  225. // directionalLight2.castShadow = true;
  226. // var directionalLight3 = createDLight( 0xffffff, 0.15 );
  227. // directionalLight3.position.copy(new THREE.Vector3( 0 , 100 , 65 ));
  228. // directionalLight3.castShadow = true;
  229. //scene.add( directionalLight );
  230. // scene.add( directionalLight2 );
  231. // scene.add( directionalLight3 );
  232. }
  233. function load(k,path) {
  234. _textures[k] = loader.load(path, THREE.SphericalRefractionMapping);
  235. }
  236. function loadTextures() {
  237. manager.onProgress = function () {
  238. console.log("Progress");
  239. }
  240. manager.onLoad = function(){
  241. console.log("[-] Textures Loaded!")
  242. computeGraph();
  243. }
  244. //load('sun','textures/planets/sun.jpg');
  245. }
  246. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  247. var earth,moon,sun,europa;
  248. function computeGraph() {
  249. return true;
  250. }
  251. // Input Handling
  252. var axis = X_AXIS;
  253. var degrees = 0;
  254. window.onkeydown = function (e) {
  255. if(e.keyCode == 65){ // a
  256. moveVector.x = -1;
  257. }
  258. else if(e.keyCode == 87){ // w
  259. moveVector.y = -1;
  260. }
  261. else if(e.keyCode == 68){ // d
  262. moveVector.x = 1;
  263. }
  264. else if(e.keyCode == 83){ // s
  265. moveVector.y = 1;
  266. }
  267. if(e.keyCode == 73){
  268. lookVector.z = -1;
  269. lookVector.x = 0;
  270. lookVector.y = 0;
  271. }
  272. else if(e.keyCode == 75){
  273. lookVector.z = 1;
  274. lookVector.x = 0;
  275. lookVector.y = 0;
  276. }
  277. if(e.keyCode == 74){
  278. lookVector.x = -1;
  279. lookVector.y = 0;
  280. lookVector.z = 0;
  281. }
  282. else if(e.keyCode == 76){
  283. lookVector.x = 1;
  284. lookVector.y = 0;
  285. lookVector.z = 0;
  286. }
  287. if(e.keyCode == 79){ //o
  288. lookVector.y = 1;
  289. lookVector.z = 0;
  290. lookVector.x = 0;
  291. }
  292. else if(e.keyCode == 85){ //u
  293. lookVector.y = -1;
  294. lookVector.z = 0;
  295. lookVector.x = 0;
  296. }
  297. if(e.keyCode == 32){
  298. GameBox.progressToNext();
  299. }
  300. console.log(e.keyCode);
  301. };
  302. window.onkeyup = function (e) {
  303. if(e.keyCode == 65){ // a
  304. moveVector.x = 0;
  305. }
  306. else if(e.keyCode == 87){ // w
  307. moveVector.y = 0;
  308. }
  309. else if(e.keyCode == 68){ // d
  310. moveVector.x = 0;
  311. }
  312. else if(e.keyCode == 83){ // s
  313. moveVector.y = 0;
  314. }
  315. // if(e.keyCode == 73){
  316. // lookVector.y = 0;
  317. // }
  318. // else if(e.keyCode == 75){
  319. // lookVector.y = 0;
  320. // }
  321. // if(e.keyCode == 74){
  322. // lookVector.x = 0;
  323. // }
  324. // else if(e.keyCode == 76){
  325. // lookVector.x = 0;
  326. // }
  327. if(e.keyCode == 80){
  328. paused = !paused;
  329. }
  330. };
  331. var raycaster = new THREE.Raycaster();
  332. var dragging = false;
  333. window.onmousedown = function (event) {
  334. // var mx = ( event.clientX / window.innerWidth ) * 2 - 1;
  335. // var my = - ( event.clientY / window.innerHeight ) * 2 + 1;
  336. // var mouse = new THREE.Vector2(mx,my);
  337. // // update the picking ray with the camera and mouse position
  338. // raycaster.setFromCamera( mouse, Game.camera );
  339. // // calculate objects intersecting the picking ray
  340. // var intersects = raycaster.intersectObjects( Game.scene.children, true );
  341. // if(intersects.length){
  342. // dragging = intersects[0].object;
  343. // }
  344. };
  345. window.onmouseup = function (event) {
  346. dragging = false;
  347. };
  348. var lastmx=0,lastmy=0;
  349. window.onmousemove = function (event) {
  350. if(dragging){
  351. var mx = ( event.clientX / window.innerWidth ) * 2 - 1;
  352. var my = - ( event.clientY / window.innerHeight ) * 2 + 1;
  353. var dx = (mx - lastmx)*30;
  354. var dy = (my - lastmy)*30;
  355. lastmx = mx;
  356. lastmy = my;
  357. if(typeof dx != "number" || typeof dy != "number" )return;
  358. switch(axis){
  359. case 1 :
  360. dragging.position.x += dx;
  361. break;
  362. case 2 :
  363. dragging.position.y += dy;
  364. break;
  365. case 3 :
  366. dragging.position.z += dx;
  367. break;
  368. }
  369. }
  370. };
  371. ///////////////////////// HELPERS /////////////////////////////////
  372. function createSkybox(scene) {
  373. /////////////////////////////////////////////////////////////////////
  374. ///// SKYBOX
  375. var urlPrefix = "textures/skybox/Daylight Box_";
  376. var urls = [ "Left.bmp", "Right.bmp",
  377. "Top.bmp", "Bottom.bmp",
  378. "Back.bmp", "Front.bmp" ];
  379. scene.background = new THREE.CubeTextureLoader()
  380. .setPath( urlPrefix )
  381. .load(urls);
  382. return;
  383. }
  384. function createBox(x,y,z,color){
  385. // This is where introtowebgl uses CubeGeometry
  386. var geometry = new THREE.BoxGeometry(x,y,z);
  387. //var material = new THREE.MeshBasicMaterial({ color: color, shading : THREE.SmoothShading });
  388. var material = new THREE.MeshPhongMaterial( {
  389. color: color,
  390. specular: 0x050505,
  391. shininess: 100
  392. } );
  393. var cube = new THREE.Mesh(geometry,material);
  394. return cube;
  395. }
  396. function generateHeight( width, height ) {
  397. var size = width * height, data = new Uint8Array( size ),
  398. perlin = new ImprovedNoise(), quality = 1, z = Math.random() * 100;
  399. for ( var j = 0; j < 4; j ++ ) {
  400. for ( var i = 0; i < size; i ++ ) {
  401. var x = i % width, y = ~~ ( i / width );
  402. data[ i ] += Math.abs( perlin.noise( x / quality, y / quality, z ) * quality * 1.75 );
  403. }
  404. quality *= 5;
  405. }
  406. return data;
  407. }
  408. function createTerrain(w,h,color){
  409. var geometry = new THREE.PlaneGeometry( w, h, w/8, h/8);
  410. var vertices = geometry.vertices;
  411. var NOISE = generateHeight(w/8+1,h/8+1);
  412. for ( var i = 0, l = vertices.length; i < l; i ++) {
  413. vertices[ i ].z = NOISE[ i ] + 10;
  414. }
  415. var texture = new THREE.TextureLoader().load( "textures/terrains/desertrock.jpg" );
  416. texture.wrapS = THREE.RepeatWrapping;
  417. texture.wrapT = THREE.RepeatWrapping;
  418. texture.repeat.set( w/64, w/64 );
  419. //var material = new THREE.MeshBasicMaterial( {color: color, side: THREE.DoubleSide} );
  420. var material = new THREE.MeshPhongMaterial({
  421. specular: 0x030303,
  422. map : texture,
  423. color : color,
  424. alphaTest: 0.8,
  425. shininess: 2,
  426. side: THREE.DoubleSide,
  427. shading : THREE.SmoothShading
  428. });
  429. var plane = new THREE.Mesh( geometry, material );
  430. return plane;
  431. }
  432. init();
  433. })();