forked from makesites/construct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.js
725 lines (582 loc) · 17.8 KB
/
views.js
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
// Add models after dependencies are loaded
construct.promise.add(function(){
//require(["backbone.app", "jquery.three"], function(){
// reference in the APP namespace
if( typeof APP == "undefined" ) window.APP = {};
// fallbacks
var Model = APP.Model || Backbone.Model;
var Collection = APP.Collection || Backbone.Collection;
var View = APP.View || Backbone.View;
var Layout = APP.Layout || Backbone.Layout;
// extend APP namespace
APP.Layers = {};
APP.Meshes = {};
APP.Sprites = {};
APP.Actors = {};
// Helper methods
var setupState = function(){
//var state = View.prototype.state || new Backbone.Model();
var state = new Backbone.Model();
if( typeof this.state == "object" ){
// if already instantiated
if( this.state.toJSON ) this.state = this.state.toJSON();
state.set( this.state );
}
return state;
};
var setupParams = function(){
//var fn = this.parent('name', options);
var params = new APP.Models.Params();
if(typeof this.params == "object" ){
// if already instantiated
if( this.params.toJSON ) this.params = this.params.toJSON();
params.set( this.params );
}
return params;
};
APP.Views.Main3D = View.extend({
el: ".main",
options: {
renderTarget: "shadow-root",
autoRender: false
},
state: {
paused: false
},
initialize: function( options ){
//
_.bindAll(this, "setup");
// main container(s)
this.objects = new APP.Collections.Objects();
this.layers = new APP.Models.Layers();
this.state = this.setupState();
this.params = this.setupParams();
if( typeof this.el !== "undefined" ){
// initiate $3d with some latency to let the DOM "rest"
setTimeout(this.setup, 100);
}
// events
this.objects.on("find", _.bind(this._find, this) );
this.layers.on("find", _.bind(this._find, this) );
this.objects.on("lod", _.bind(this._updateLOD, this) );
this.layers.on("lod", _.bind(this._updateLOD, this) );
this.objects.on("pause", _.bind(this.togglePause, this) );
this.on("pause", _.bind(this.togglePause, this) );
return View.prototype.initialize.call( this, options );
},
// create the 3D environment (watch for live updates)
setup: function(){
this.$3d = $(this.el).three({ watch: true }, _.bind(this._start, this) );
$("body").on("update", this.el, _.bind(this._update, this) );
},
// shims for older Backbone.APP
setupParams: setupParams,
setupState: setupState,
// when the 3D environement is ready
start: function( $3d ){
},
// trigger on every frame
update: function(){
},
// Internal
_start: function( $3d ){
// automatic startup
// - save Three.js instance
this.$3d = $3d;
this.$3d.clock = new THREE.Clock(); // one clock for all $3d?
// now start the rendering
this.render();
// user-defined startup
this.start( $3d );
},
_update: function( e ){
// only update if the event is of the container
if( this.el !== e.target.el) return;
// automatic updates
// - broadcast updates to objects
for( var i in this.objects.attributes ){
this.objects.get(i).trigger("update", e);
}
for( var j in this.layers.attributes ){
this.layers.get(j).trigger("update", e);
}
// user-defined updates
this.update( e );
},
_updateLOD: function( object ){
if( !this.$3d.active.camera ) return;
object.update( this.$3d.active.camera );
},
_find: function( e ){
// where is the data id located in relation to this.el
var id = ( $(e.el).find("[data-id]").length > 0 ) ? $(e.el).find("[data-id]").attr("data-id") : $(e.el).attr("data-id");
if( !_.isUndefined(id) ){
var object = this.$3d.get(id);
// save a reference to that object
e.object = object;
// trigger start event
e.trigger("start");
}
},
togglePause: function( e ){
this.state.set('paused', !this.state.get('paused') ); // toggle
// update 3d
this.$3d.options.paused = this.state.get('paused');
},
_unPause: function(){
this.state.set('paused', false); // toggle
// update 3d
this.$3d.options.paused = false;
// event
this.trigger("unpause");
}
});
// Meshes
// in case APP.Mesh has already been defined by a plugin
var Mesh = APP.Mesh || View;
// move speed, collission to dynamic mesh...
APP.Mesh = Mesh.extend({
options: {
speed: false,
bind: "sync"
},
events: {
//"css-filter": "_customFilter"
},
state: {
rendered: false
},
initialize: function( options ){
options = options || {};
// FIX: reject collections
if (options.models ) return; // should this be option.collection?
this.state = this.setupState();
this.params = this.setupParams();
// data
this.data = this.data || options.data || this.model || new APP.Models.Mesh();
if (options.params ) this.params.set( options.params );
// find the parent
this.trigger("parent");
// events
this.on("update", _.bind(this._update, this));
this.on("start", _.bind(this._start, this));
// bind class methods
_.bindAll(this, '_updateLOD');
this._setupEvents(); // events object isn't working...
var self = this;
// HACK!!! wait till the parent arrives...
setTimeout(function(){
return Mesh.prototype.initialize.call(self, options);
}, 100);
},
// shims for older Backbone.APP
setupParams: setupParams,
setupState: setupState,
start: function(){
},
toJSON: function(){
var json = {};
//
json.data = this._toJSON();
json.params = this.params.toJSON();
// #43 - adding options to the template data
if( this.options.inRender ) json.options = this.options;
//
return json;
},
// set the initial attributes (once)
_start: function(){
// lookup attributes
// - position
var position = this.data.get("position");
var defaultPosition = APP.Models.Mesh.prototype.defaults.position;
if( !_.isUndefined(position) && position !== defaultPosition ){
this.object.position.set( position[0], position[1], position[2] );
}
// - rotation
var rotation = this.data.get("rotation");
var defaultRotation = APP.Models.Mesh.prototype.defaults.rotation;
if( !_.isUndefined(rotation) && rotation !== defaultRotation ){
this.object.rotation.set( rotation[0], rotation[1], rotation[2] );
}
// - scale
var scale = this.data.get("scale");
var defaultScale = APP.Models.Mesh.prototype.defaults.scale;
if( !_.isUndefined(scale) && scale !== defaultScale ){
this.object.scale.set( scale[0], scale[1], scale[2] );
}
// user defined actions
this.start();
},
_preRender: function(){
// FIX: if el is empty div, delete it!
if( this.el ){
var html = $("<body></body>").append( this.el ).html().toString();
if( html == "<div></div>" ) delete this.el; // will be recreated in render()
}
// app-specific actions
this.preRender();
},
render: function(){
// limit to single render
if( this.state.get('rendered') ) return;
// continue..
return Mesh.prototype.render.call(this);
},
_postRender: function(){
// set state
this.state.set('rendered', true);
this.trigger("render");
return Mesh.prototype._postRender.call(this);
},
_update: function( e ){
var self = this;
// FIX: if there's no reference to the object yet, request it again
// (and stop further processing)
if( _.isUndefined(this.object) ){
//console.log("render", this);
return this.trigger("render");
}
// FIX: if object is null it was deleted from the $3d environment.
if( _.isNull(this.object) ) return this.disable();
// set the speed of the object
if( this.options.speed && this.object ){
// variables
var speed = this.options.speed;
var position = this.object.position;
if(speed.x) position.x += speed.x;
if(speed.y) position.y += speed.y;
if(speed.z) position.z += speed.z;
// check if position has changed first
this.object.position.set( position.x, position.y, position.z );
}
// update level of detail
if( this.object && this.object.objects ){
this._updateLOD( this.object );
}
if( this.objects ){
// - broadcast updates to objects
for( var i in this.objects.attributes ){
this.objects.get(i).trigger("update", e);
}
}
// user-defined updates
this.update( e );
},
update: function( e ){
// executed on every tick
},
// trigger with debounce!
_updateLOD: function(){
this.trigger("lod", this.object);
},
remove: function(){
//console.log("remove", View.prototype.remove );
this.trigger("remove", this);
// remove object from scene
// (should this be automated by removing the tags?)
var scene = this.object.parent;
if (scene) scene.remove( this.object );
// also remove from $3d.objects list (not implemented yet)
// unbind events
this.undelegateEvents();
this.$el.removeData().unbind();
//Remove view from DOM
return Mesh.prototype.remove.call(this);
},
// delete view logic without, leave the markup
disable: function(){
// events
this.off("update", _.bind(this._update, this));
this.off("start", _.bind(this._start, this));
//
},
// Placeholders
customFilter: function(){
},
// Internal
// - validate is required in backbone models
_validate: function(){
return true;
},
// setup events
_setupEvents: function(){
// events
$(this.el).on('css-filter',_.bind(this._customFilter, this) );
//this.el.addEventListener('css-filter', function(){ console.log("dodododod"); }, false);
},
_customFilter: function(){
// user actions
this.customFilter();
}
});
/* extending Mesh */
// a static mesh cannot be updated after init
APP.Meshes.Static = APP.Mesh.extend({
});
// a dynamic mesh can be updated after init
APP.Meshes.Dynamic = APP.Meshes.Static.extend({
options: {
moveStep: 3, // a 0-10 setting
rotateStep: 0.5 // 1-0 settting
},
params: {
// moving conventions as set by THREE.FlyControls
move: {
left: 0,
right: 0,
up: 0,
down: 0,
forward: 0,
back: 0,
pitchDown: 0,
pitchUp: 0,
yawRight: 0,
yawLeft: 0,
rollRight: 0,
rollLeft: 0
}
},
initialize: function( options ){
// containers
this.objects = new APP.Collections.Objects();
// events
this.objects.on("find", _.bind(this._find, this) );
this.objects.on("parent", _.bind(this._self, this) );
return APP.Meshes.Static.prototype.initialize.call( this, options );
},
_find: function( e ){
this.trigger("find", e);
},
_self: function( e ){
e.parent = (this.object) ? this.object : null;
},
tmpQuaternion: new THREE.Quaternion(),
moveVector: new THREE.Vector3( 0, 0, 0 ),
rotationVector: new THREE.Vector3( 0, 0, 0 ),
updateMovementVector: function() {
var move = this.params.get('move');
this.moveVector.x = ( -move.left + move.right );
this.moveVector.y = ( -move.down + move.up );
this.moveVector.z = ( -move.forward + move.back );
//console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
},
updateRotationVector: function() {
var move = this.params.get('move');
this.rotationVector.x = ( -move.pitchDown + move.pitchUp );
this.rotationVector.y = ( -move.yawRight + move.yawLeft );
this.rotationVector.z = ( -move.rollRight + move.rollLeft );
//console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
}
});
// an avatar has "entity" qualities
APP.Meshes.Avatar = APP.Meshes.Dynamic.extend({
});
/* extending Avatar */
// a non-playable character
APP.Meshes.NPC = APP.Meshes.Avatar.extend({
});
// a playable character
APP.Meshes.Player = APP.Meshes.Avatar.extend({
});
// Sprites
APP.Sprite = View.extend({
initialize: function( options ){
options = options || {};
// FIX: reject collections
if (options.models ) return;
//
this.state = this.setupState();
this.params = this.setupParams();
// data
this.data = this.data || options.data || this.model || new APP.Models.Sprite();
if (options.params ) this.params.set( options.params );
this.object = options.object;
// events
this.on("update", _.bind(this._update, this));
//this.on("start", _.bind(this._start, this));
if( this._start ) this._start();
var self = this;
// HACK!!! wait till the parent arrives...
setTimeout(function(){
return View.prototype.initialize.call(self, options);
}, 100);
},
// shims for older Backbone.APP
setupParams: setupParams,
setupState: setupState,
_start: function(){
},
_update: function(){
},
// merge with APP.Mesh.toJSON ?
toJSON: function(){
var json = {};
//
json.data = this._toJSON();
json.params = this.params.toJSON();
// #43 - adding options to the template data
if( this.options.inRender ) json.options = this.options;
//
return json;
}
});
/* extending Sprite */
APP.Sprites.Static = APP.Sprite.extend({
});
// based on : http://stemkoski.github.io/Three.js/Texture-Animation.html
APP.Sprites.Animated = APP.Sprite.extend({
options: {
timeElapsed: 0
},
_start: function(){
var texture = this.object.children[0].material.map;
// put all these variables in this.options or this.state...
var tiles = this.model.get("tiles");
this.tilesHorizontal = tiles[0];
this.tilesVertical = tiles[1];
// how many images does this spritesheet contain?
// usually equals tilesHoriz * tilesVert, but not necessarily,
// if there at blank tiles at the bottom of the spritesheet.
this.numberOfTiles = this.model.get("total");
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 1 / this.tilesHorizontal, 1 / this.tilesVertical );
// how long should each image be displayed?
this.tileDisplayDuration = this.model.get("timeout");
// how long has the current image been displayed?
this.currentDisplayTime = 0;
// which image is currently being displayed?
this.currentTile = 0;
this.options.lastTime = (new Date()).getTime();
return APP.Sprite.prototype._start.call(this);
},
_update: function( e ){
var now = (new Date()).getTime(),
timeElapsed = now - this.options.lastTime;
//this.currentDisplayTime += timeElapsed;
var texture = this.object.children[0].material.map;
if (timeElapsed > this.tileDisplayDuration)
{
//this.currentDisplayTime -= this.tileDisplayDuration;
this.options.lastTime = now;
this.currentTile++;
if (this.currentTile == this.numberOfTiles)
this.currentTile = 0;
var currentColumn = this.currentTile % this.tilesHorizontal;
texture.offset.x = currentColumn / this.tilesHorizontal;
var currentRow = Math.floor( this.currentTile / this.tilesHorizontal );
texture.offset.y = 1 - currentRow / this.tilesVertical;
}
return APP.Sprite.prototype._update.call(this, e);
}
});
APP.Views.Asset = View.extend({
// user jquery-three for rendering
// attach dat.gui view if editable & user has admin rights
});
// Layers
// - Main layer construct
APP.Layer = Backbone.Collection.extend({
/*
options: {
append: true
},
*/
initialize: function( models, options ){
// fallbacks
models = models || [];
// base objects
this.el = this.el || options.el || null;
this.objects = new APP.Collections.Objects();
// events
//if( options.collection ){
// models = options.collection;
// delete options.collection;
for(var i = 0; i < models.length ; i++){
var model = models.get(i) || {};
this.add( model );
}
//}
// events
this.on("update", _.bind(this._update, this) );
this.objects.on("find", _.bind(this._find, this) );
this.objects.on("lod", _.bind(this._bubbleLOD, this) );
this.objects.on("change", _.bind(this._refresh, this) );
//this.object = options.object || this.options.object || this.object || APP.Mesh;
return APP.Collection.prototype.initialize.call(this, null, options);
},
add: function( data ){
data = data || {};
// treat a collection update differently
if( data.models ) return this.addCollection( data );
// create new object from blueprint
var object = new this.object({
parentEl: this.el,
//renderTarget: this.el,
append: true
});
this.objects.add( object );
// save data
data.id = object._name || object.id || null;
// exit now if no id is
var model = new Backbone.Model(data);
// set the data in the collection
return Backbone.Collection.prototype.add.call(this, model);
},
addCollection: function( collection ){
var data = collection.toJSON(); // collection not this?
var models = this.models;
for( var i in data ){
//console.log("data[i]", data[i], i, this.at(i) );
// get the model from the existing collection
// if there's an id match that, otherwise match position
var id = this._matchData(data[i], i);
if( id ) data[i].id = id;
var model = ( id ) ? this.get(id) : this.at(i);
if( model ){
// update the existing collection
model.set( data[i] ); // silent?
} else {
// create a new model
this.set( data[i], { merge: false, add: true, remove: false });
}
}
// update models
//this.set( data.models );
},
update: function( e ){
},
refresh: function( e ){
},
// Internal
_update: function( e ){
// automatic updates
// - broadcast updates to objects
for( var i in this.objects.attributes ){
this.objects.get(i).trigger("update", e);
}
// user-defined updates
this.update( e );
},
// match data with an object
_matchData: function(data, index){
var lookupID = ( data.id );
var ids = Object.keys( this.objects.toJSON() );
if( data.id && ids.indexOf(data.id) > 0 ) return data.id;
if( ids[index] ) return ids[index];
return null; // new model?
},
// when the objects collection has changed:
_refresh: function( e ){
// user defined
this.refresh( e );
},
_find: function( e ){
this.trigger("find", e);
},
_bubbleLOD: function( e ){
this.trigger("lod", e);
}
});
//});
});