PropertyBinding.js 10.8 KB
Newer Older
1 2 3 4 5 6 7 8
/**
 *
 * A track bound to a real value in the scene graph.
 * 
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 */

9
THREE.PropertyBinding = function ( rootNode, trackName ) {
10 11 12

	this.rootNode = rootNode;
	this.trackName = trackName;
13 14
	this.referenceCount = 0;
	this.originalValue = null; // the value of the property before it was controlled by this binding
15

16
	var parseResults = THREE.PropertyBinding.parseTrackName( trackName );
17

B
Ben Houston 已提交
18
	//console.log( parseResults );
19
	this.directoryName = parseResults.directoryName;
20
	this.nodeName = parseResults.nodeName;
B
Ben Houston 已提交
21 22
	this.objectName = parseResults.objectName;
	this.objectIndex = parseResults.objectIndex;
23 24
	this.propertyName = parseResults.propertyName;
	this.propertyIndex = parseResults.propertyIndex;
25

26
	this.node = THREE.PropertyBinding.findNode( rootNode, this.nodeName );
27

28 29
	this.cumulativeValue = null;
	this.cumulativeWeight = 0;
30 31
};

32
THREE.PropertyBinding.prototype = {
33

34
	constructor: THREE.PropertyBinding,
35

36
	reset: function() {
37

38 39
		this.cumulativeValue = null;
		this.cumulativeWeight = 0;
40

41 42 43 44
	},

	accumulate: function( value, weight ) {
		
45
		if( this.cumulativeWeight === 0 ) {
46

47 48
			if( this.cumulativeValue === null ) {
				this.cumulativeValue = THREE.AnimationUtils.clone( value );
49
			}
50 51 52 53 54
			this.cumulativeWeight = weight;
			//console.log( this );

		}
		else {
55

56 57 58 59
			var lerpAlpha = weight / ( this.cumulativeWeight + weight );
			this.cumulativeValue = this.lerp( this.cumulativeValue, value, lerpAlpha );
			this.cumulativeWeight += weight;
			//console.log( this );
60

61 62
		}

63 64 65 66 67
	},

	unbind: function() {

		if( ! this.setValue ) throw new Error( "can not unbind if not bound in the first place." );
68

69
		this.setValue( this.originalValue );
70
	},
71

72 73 74 75
	// creates the member functions:
	//	- setValue( value )
	//  - getValue()
	//  - triggerDirty()
76

77
	bind: function() {
78

79 80 81
		if( this.setValue ) throw new Error( "can not bind if already bound." );
		
		//console.log( "PropertyBinding", this );
82

83
		var equalsFunc = THREE.AnimationUtils.getEqualsFunc( this.cumulativeValue );
84

85
		var targetObject = this.node;
86

87 88 89 90 91
 		// ensure there is a value node
		if( ! targetObject ) {
			console.error( "  trying to update node for track: " + this.trackName + " but it wasn't found." );
			return;
		}
92

93 94 95 96 97 98
		if( this.objectName ) {
			// special case were we need to reach deeper into the hierarchy to get the face materials....
			if( this.objectName === "materials" ) {
				if( ! targetObject.material ) {
					console.error( '  can not bind to material as node does not have a material', this );
					return;				
99
				}
100 101 102
				if( ! targetObject.material.materials ) {
					console.error( '  can not bind to material.materials as node.material does not have a materials array', this );
					return;				
103
				}
104 105 106 107 108
				targetObject = targetObject.material.materials;
			}
			else if( this.objectName === "bones" ) {
				if( ! targetObject.skeleton ) {
					console.error( '  can not bind to bones as node does not have a skeleton', this );
109
				}
110 111 112
				targetObject = targetObject.skeleton.bones;

				// TODO/OPTIMIZE, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
113
				
114 115 116 117 118 119 120
				// support resolving morphTarget names into indices.
				//console.log( "  resolving bone name: ", this.objectIndex );
				for( var i = 0; i < this.node.skeleton.bones.length; i ++ ) {
					if( this.node.skeleton.bones[i].name === this.objectIndex ) {
						//console.log( "  resolved to index: ", i );
						this.objectIndex = i;
						break;
121
					}
122
				}
123 124
			}
			else {
125

126 127 128 129 130
				if( targetObject[ this.objectName ] === undefined ) {
					console.error( '  can not bind to objectName of node, undefined', this );			
					return;
				}
				targetObject = targetObject[ this.objectName ];
131
			}
132 133 134 135 136 137
			
			if( this.objectIndex !== undefined ) {
				if( targetObject[ this.objectIndex ] === undefined ) {
					console.error( "  trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
					return;				
				}
138

139
				targetObject = targetObject[ this.objectIndex ];
140 141
			}

142
		}
143

144 145 146 147 148 149
 		// special case mappings
 		var nodeProperty = targetObject[ this.propertyName ];
		if( ! nodeProperty ) {
			console.error( "  trying to update property for track: " + this.nodeName + '.' + this.propertyName + " but it wasn't found.", targetObject );				
			return;
		}
150

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
		// access a sub element of the property array (only primitives are supported right now)
		if( this.propertyIndex !== undefined ) {

			if( this.propertyName === "morphTargetInfluences" ) {
				// TODO/OPTIMIZE, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
				
				// support resolving morphTarget names into indices.
				//console.log( "  resolving morphTargetInfluence name: ", this.propertyIndex );
				if( ! this.node.geometry ) {
					console.error( '  can not bind to morphTargetInfluences becasuse node does not have a geometry', this );				
				}
				if( ! this.node.geometry.morphTargets ) {
					console.error( '  can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );				
				}
				
				for( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
					if( this.node.geometry.morphTargets[i].name === this.propertyIndex ) {
						//console.log( "  resolved to index: ", i );
						this.propertyIndex = i;
						break;
171
					}
172 173
				}
			}
174

175 176 177 178 179
			//console.log( '  update property array ' + this.propertyName + '[' + this.propertyIndex + '] via assignment.' );				
			this.setValue = function( value ) {
				if( ! equalsFunc( nodeProperty[ this.propertyIndex ], value ) ) {
					nodeProperty[ this.propertyIndex ] = value;
					return true;
180
				}
181 182 183 184 185 186
				return false;
			};

			this.getValue = function() {
				return nodeProperty[ this.propertyIndex ];
			};
187

188 189 190 191 192 193 194 195 196
		}
		// must use copy for Object3D.Euler/Quaternion		
		else if( nodeProperty.copy ) {
			
			//console.log( '  update property ' + this.name + '.' + this.propertyName + ' via a set() function.' );				
			this.setValue = function( value ) {
				if( ! equalsFunc( nodeProperty, value ) ) {
					nodeProperty.copy( value );
					return true;
197
				}
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
				return false;
			}

			this.getValue = function() {
				return nodeProperty;
			};

		}
		// otherwise just set the property directly on the node (do not use nodeProperty as it may not be a reference object)
		else {

			//console.log( '  update property ' + this.name + '.' + this.propertyName + ' via assignment.' );				
			this.setValue = function( value ) {
				if( ! equalsFunc( targetObject[ this.propertyName ], value ) ) {
					targetObject[ this.propertyName ] = value;	
					return true;
214
				}
215
				return false;
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
			this.getValue = function() {
				return targetObject[ this.propertyName ];
			};

		}

		// trigger node dirty			
		if( targetObject.needsUpdate !== undefined ) { // material
			
			//console.log( '  triggering material as dirty' );
			this.triggerDirty = function() {
				this.node.needsUpdate = true;
			}

		}			
		else if( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
			
			//console.log( '  triggering node as dirty' );
			this.triggerDirty = function() {
				targetObject.matrixWorldNeedsUpdate = true;
			}

		}

		this.originalValue = this.getValue();

		this.lerp = THREE.AnimationUtils.getLerpFunc( value, true );

	},

	apply: function() {

		// for speed capture the setter pattern as a closure (sort of a memoization pattern: https://en.wikipedia.org/wiki/Memoization)
		if( ! this.setValue ) {
			this.bind();
253 254
		}

255
		// early exit if there is nothing to apply.
B
Ben Houston 已提交
256 257
		if( this.cumulativeWeight > 0 ) {
		
258 259 260 261 262 263 264 265 266 267
			// blend with original value
			if( this.cumulativeWeight < 1 ) {

				var remainingWeight = 1 - this.cumulativeWeight;
				var lerpAlpha = remainingWeight / ( this.cumulativeWeight + remainingWeight );
				this.cumulativeValue = this.lerp( this.cumulativeValue, this.originalValue, lerpAlpha );

			}

			var valueChanged = this.setValue( this.cumulativeValue );
268

B
Ben Houston 已提交
269 270 271
			if( valueChanged && this.triggerDirty ) {
				this.triggerDirty();
			}
272

273 274 275
			// reset accumulator
			this.cumulativeValue = null;
			this.cumulativeWeight = 0;
B
Ben Houston 已提交
276

277
		}
278 279 280 281 282
	}

};


283
THREE.PropertyBinding.parseTrackName = function( trackName ) {
284 285

	// matches strings in the form of:
286 287
	//    nodeName.property
	//    nodeName.property[accessor]
288
	//    nodeName.material.property[accessor]
289
	//    uuid.property[accessor]
290
	//    uuid.objectName[objectIndex].propertyName[propertyIndex]
291 292
	//    parentName/nodeName.property
	//    parentName/parentName/nodeName.property[index]
293
	//	  .bone[Armature.DEF_cog].position
294 295
	// created and tested via https://regex101.com/#javascript

296
	var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/; 
297 298 299 300 301 302 303 304 305 306
	var matches = re.exec(trackName);

	if( ! matches ) {
		throw new Error( "cannot parse trackName at all: " + trackName );
	}

    if (matches.index === re.lastIndex) {
        re.lastIndex++;
    }

307
	var results = {
308
		directoryName: matches[1],
B
Ben Houston 已提交
309
		nodeName: matches[3], 	// allowed to be null, specified root node.
310 311 312 313
		objectName: matches[5],
		objectIndex: matches[7],
		propertyName: matches[9],
		propertyIndex: matches[11]	// allowed to be null, specifies that the whole property is set.
314 315
	};

316
	//console.log( "PropertyBinding.parseTrackName", trackName, results, matches );
317

318 319 320 321 322
	if( results.propertyName === null || results.propertyName.length === 0 ) {
		throw new Error( "can not parse propertyName from trackName: " + trackName );
	}

	return results;
323 324 325 326

};

// TODO: Cache this at some point
327
THREE.PropertyBinding.findNode = function( root, nodeName ) {
328

329
	//console.log( 'AnimationUtils.findNode( ' + root.name + ', nodeName: ' + nodeName + ')');
330
	
331
	if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
332

333
		//console.log( '  root.' );
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
		return root;

	}

	// (2) search into skeleton bones.
	if( root.skeleton ) {

		var searchSkeleton = function( skeleton ) {

			for( var i = 0; i < skeleton.bones.length; i ++ ) {

				var bone = skeleton.bones[i];

				if( bone.name === nodeName ) {

B
Ben Houston 已提交
349
					return bone;
350 351 352 353 354 355 356 357

				}
			}

			return null;

		};

B
Ben Houston 已提交
358
		var bone = searchSkeleton( root.skeleton );
359

B
Ben Houston 已提交
360
		if( bone ) {
361

362
			//console.log( '  bone: ' + bone.name + '.' );
B
Ben Houston 已提交
363
			return bone;
364 365 366 367 368 369 370 371 372 373 374 375 376

		}
	}

	// (3) search into node subtree.
	if( root.children ) {

		var searchNodeSubtree = function( children ) {

			for( var i = 0; i < children.length; i ++ ) {

				var childNode = children[i];

377
				if( childNode.name === nodeName || childNode.uuid === nodeName ) {
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396

					return childNode;

				}

				var result = searchNodeSubtree( childNode.children );

				if( result ) return result;

			}

			return null;	

		};

		var subTreeNode = searchNodeSubtree( root.children );

		if( subTreeNode ) {

397
			//console.log( '  node: ' + subTreeNode.name + '.' );
398 399 400 401 402 403
			return subTreeNode;

		}

	}

404
	//console.log( "   <null>.  No node found for name: " + nodeName );
405 406 407

	return null;
}