CmdAddObject.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * @author dforrer / https://github.com/dforrer
  3. * Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch)
  4. */
  5. /**
  6. * @param object THREE.Object3D
  7. * @constructor
  8. */
  9. CmdAddObject = function ( object ) {
  10. Cmd.call( this );
  11. this.type = 'CmdAddObject';
  12. this.object = object;
  13. if ( object !== undefined ) {
  14. this.name = 'Add Object: ' + object.name;
  15. }
  16. };
  17. CmdAddObject.prototype = {
  18. execute: function () {
  19. this.editor.addObject( this.object );
  20. this.editor.select( this.object );
  21. },
  22. undo: function () {
  23. this.editor.removeObject( this.object );
  24. this.editor.deselect();
  25. },
  26. toJSON: function () {
  27. var output = Cmd.prototype.toJSON.call( this );
  28. this.object.updateMatrixWorld( true );
  29. var meta = {
  30. geometries: {},
  31. materials: {},
  32. textures: {},
  33. images: {}
  34. };
  35. var json = this.object.toJSON( meta );
  36. var geometries = extractFromCache( meta.geometries );
  37. var materials = extractFromCache( meta.materials );
  38. var textures = extractFromCache( meta.textures );
  39. var images = extractFromCache( meta.images );
  40. if ( geometries.length > 0 ) json.geometries = geometries;
  41. if ( materials.length > 0 ) json.materials = materials;
  42. if ( textures.length > 0 ) json.textures = textures;
  43. if ( images.length > 0 ) json.images = images;
  44. output.object = json;
  45. return output;
  46. // Note: The function 'extractFromCache' is copied from Object3D.toJSON()
  47. // extract data from the cache hash
  48. // remove metadata on each item
  49. // and return as array
  50. function extractFromCache ( cache ) {
  51. var values = [];
  52. for ( var key in cache ) {
  53. var data = cache[ key ];
  54. delete data.metadata;
  55. values.push( data );
  56. }
  57. return values;
  58. }
  59. },
  60. fromJSON: function ( json ) {
  61. Cmd.prototype.fromJSON.call( this, json );
  62. this.object = this.editor.objectByUuid( json.object.object.uuid );
  63. if ( this.object === undefined ) {
  64. var loader = new THREE.ObjectLoader();
  65. this.object = loader.parse( json.object );
  66. }
  67. }
  68. };