Player.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var Player = function ( editor ) {
  5. var signals = editor.signals;
  6. var container = new UI.Panel();
  7. container.setPosition( 'absolute' );
  8. container.setDisplay( 'none' );
  9. //
  10. var camera, scene, renderer;
  11. var scripts;
  12. //
  13. var load = function ( json ) {
  14. renderer = new THREE.WebGLRenderer( { antialias: true } );
  15. renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );
  16. container.dom.appendChild( renderer.domElement );
  17. camera = editor.camera.clone();
  18. scene = new THREE.ObjectLoader().parse( json );
  19. //
  20. scripts = [];
  21. scene.traverse( function ( child ) {
  22. if ( child.script !== undefined ) {
  23. var script = new Function( 'scene', 'time', child.script.source ).bind( child );
  24. scripts.push( script );
  25. }
  26. } );
  27. };
  28. var request;
  29. var play = function () {
  30. request = requestAnimationFrame( play );
  31. update();
  32. render();
  33. };
  34. var stop = function () {
  35. cancelAnimationFrame( request );
  36. if ( renderer !== undefined ) {
  37. container.dom.removeChild( renderer.domElement );
  38. }
  39. };
  40. var render = function () {
  41. renderer.render( scene, camera );
  42. };
  43. var update = function () {
  44. var time = performance.now();
  45. for ( var i = 0; i < scripts.length; i ++ ) {
  46. scripts[ i ]( scene, time );
  47. }
  48. render();
  49. };
  50. signals.startPlayer.add( function ( json ) {
  51. container.setDisplay( '' );
  52. load( json );
  53. play();
  54. } );
  55. signals.stopPlayer.add( function () {
  56. container.setDisplay( 'none' );
  57. stop();
  58. } );
  59. return container;
  60. };