PropertyBinding.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /**
  2. *
  3. * A reference to a real property in the scene graph.
  4. *
  5. *
  6. * @author Ben Houston / http://clara.io/
  7. * @author David Sarno / http://lighthaus.us/
  8. * @author tschw
  9. */
  10. // Characters [].:/ are reserved for track binding syntax.
  11. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  12. var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  13. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  14. // only latin characters, and the unicode \p{L} is not yet supported. So
  15. // instead, we exclude reserved characters and match everything else.
  16. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  17. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  19. // be matched to parse the rest of the track name.
  20. var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  21. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  22. var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  23. // Object on target node, and accessor. May not contain reserved
  24. // characters. Accessor may contain any character except closing bracket.
  25. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26. // Property and accessor. May not contain reserved characters. Accessor may
  27. // contain any non-bracket characters.
  28. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  29. var _trackRe = new RegExp( ''
  30. + '^'
  31. + _directoryRe
  32. + _nodeRe
  33. + _objectRe
  34. + _propertyRe
  35. + '$'
  36. );
  37. var _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  38. function Composite( targetGroup, path, optionalParsedPath ) {
  39. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  40. this._targetGroup = targetGroup;
  41. this._bindings = targetGroup.subscribe_( path, parsedPath );
  42. }
  43. Object.assign( Composite.prototype, {
  44. getValue: function ( array, offset ) {
  45. this.bind(); // bind all binding
  46. var firstValidIndex = this._targetGroup.nCachedObjects_,
  47. binding = this._bindings[ firstValidIndex ];
  48. // and only call .getValue on the first
  49. if ( binding !== undefined ) binding.getValue( array, offset );
  50. },
  51. setValue: function ( array, offset ) {
  52. var bindings = this._bindings;
  53. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  54. bindings[ i ].setValue( array, offset );
  55. }
  56. },
  57. bind: function () {
  58. var bindings = this._bindings;
  59. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  60. bindings[ i ].bind();
  61. }
  62. },
  63. unbind: function () {
  64. var bindings = this._bindings;
  65. for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  66. bindings[ i ].unbind();
  67. }
  68. }
  69. } );
  70. function PropertyBinding( rootNode, path, parsedPath ) {
  71. this.path = path;
  72. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  73. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  74. this.rootNode = rootNode;
  75. }
  76. Object.assign( PropertyBinding, {
  77. Composite: Composite,
  78. create: function ( root, path, parsedPath ) {
  79. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  80. return new PropertyBinding( root, path, parsedPath );
  81. } else {
  82. return new PropertyBinding.Composite( root, path, parsedPath );
  83. }
  84. },
  85. /**
  86. * Replaces spaces with underscores and removes unsupported characters from
  87. * node names, to ensure compatibility with parseTrackName().
  88. *
  89. * @param {string} name Node name to be sanitized.
  90. * @return {string}
  91. */
  92. sanitizeNodeName: function ( name ) {
  93. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  94. },
  95. parseTrackName: function ( trackName ) {
  96. var matches = _trackRe.exec( trackName );
  97. if ( ! matches ) {
  98. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  99. }
  100. var results = {
  101. // directoryName: matches[ 1 ], // (tschw) currently unused
  102. nodeName: matches[ 2 ],
  103. objectName: matches[ 3 ],
  104. objectIndex: matches[ 4 ],
  105. propertyName: matches[ 5 ], // required
  106. propertyIndex: matches[ 6 ]
  107. };
  108. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  109. if ( lastDot !== undefined && lastDot !== - 1 ) {
  110. var objectName = results.nodeName.substring( lastDot + 1 );
  111. // Object names must be checked against a whitelist. Otherwise, there
  112. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  113. // 'bar' could be the objectName, or part of a nodeName (which can
  114. // include '.' characters).
  115. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  116. results.nodeName = results.nodeName.substring( 0, lastDot );
  117. results.objectName = objectName;
  118. }
  119. }
  120. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  121. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  122. }
  123. return results;
  124. },
  125. findNode: function ( root, nodeName ) {
  126. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  127. return root;
  128. }
  129. // search into skeleton bones.
  130. if ( root.skeleton ) {
  131. var bone = root.skeleton.getBoneByName( nodeName );
  132. if ( bone !== undefined ) {
  133. return bone;
  134. }
  135. }
  136. // search into node subtree.
  137. if ( root.children ) {
  138. var searchNodeSubtree = function ( children ) {
  139. for ( var i = 0; i < children.length; i ++ ) {
  140. var childNode = children[ i ];
  141. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  142. return childNode;
  143. }
  144. var result = searchNodeSubtree( childNode.children );
  145. if ( result ) return result;
  146. }
  147. return null;
  148. };
  149. var subTreeNode = searchNodeSubtree( root.children );
  150. if ( subTreeNode ) {
  151. return subTreeNode;
  152. }
  153. }
  154. return null;
  155. }
  156. } );
  157. Object.assign( PropertyBinding.prototype, { // prototype, continued
  158. // these are used to "bind" a nonexistent property
  159. _getValue_unavailable: function () {},
  160. _setValue_unavailable: function () {},
  161. BindingType: {
  162. Direct: 0,
  163. EntireArray: 1,
  164. ArrayElement: 2,
  165. HasFromToArray: 3
  166. },
  167. Versioning: {
  168. None: 0,
  169. NeedsUpdate: 1,
  170. MatrixWorldNeedsUpdate: 2
  171. },
  172. GetterByBindingType: [
  173. function getValue_direct( buffer, offset ) {
  174. buffer[ offset ] = this.node[ this.propertyName ];
  175. },
  176. function getValue_array( buffer, offset ) {
  177. var source = this.resolvedProperty;
  178. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  179. buffer[ offset ++ ] = source[ i ];
  180. }
  181. },
  182. function getValue_arrayElement( buffer, offset ) {
  183. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  184. },
  185. function getValue_toArray( buffer, offset ) {
  186. this.resolvedProperty.toArray( buffer, offset );
  187. }
  188. ],
  189. SetterByBindingTypeAndVersioning: [
  190. [
  191. // Direct
  192. function setValue_direct( buffer, offset ) {
  193. this.targetObject[ this.propertyName ] = buffer[ offset ];
  194. },
  195. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  196. this.targetObject[ this.propertyName ] = buffer[ offset ];
  197. this.targetObject.needsUpdate = true;
  198. },
  199. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  200. this.targetObject[ this.propertyName ] = buffer[ offset ];
  201. this.targetObject.matrixWorldNeedsUpdate = true;
  202. }
  203. ], [
  204. // EntireArray
  205. function setValue_array( buffer, offset ) {
  206. var dest = this.resolvedProperty;
  207. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  208. dest[ i ] = buffer[ offset ++ ];
  209. }
  210. },
  211. function setValue_array_setNeedsUpdate( buffer, offset ) {
  212. var dest = this.resolvedProperty;
  213. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  214. dest[ i ] = buffer[ offset ++ ];
  215. }
  216. this.targetObject.needsUpdate = true;
  217. },
  218. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  219. var dest = this.resolvedProperty;
  220. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  221. dest[ i ] = buffer[ offset ++ ];
  222. }
  223. this.targetObject.matrixWorldNeedsUpdate = true;
  224. }
  225. ], [
  226. // ArrayElement
  227. function setValue_arrayElement( buffer, offset ) {
  228. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  229. },
  230. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  231. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  232. this.targetObject.needsUpdate = true;
  233. },
  234. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  235. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  236. this.targetObject.matrixWorldNeedsUpdate = true;
  237. }
  238. ], [
  239. // HasToFromArray
  240. function setValue_fromArray( buffer, offset ) {
  241. this.resolvedProperty.fromArray( buffer, offset );
  242. },
  243. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  244. this.resolvedProperty.fromArray( buffer, offset );
  245. this.targetObject.needsUpdate = true;
  246. },
  247. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  248. this.resolvedProperty.fromArray( buffer, offset );
  249. this.targetObject.matrixWorldNeedsUpdate = true;
  250. }
  251. ]
  252. ],
  253. getValue: function getValue_unbound( targetArray, offset ) {
  254. this.bind();
  255. this.getValue( targetArray, offset );
  256. // Note: This class uses a State pattern on a per-method basis:
  257. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  258. // prototype version of these methods with one that represents
  259. // the bound state. When the property is not found, the methods
  260. // become no-ops.
  261. },
  262. setValue: function getValue_unbound( sourceArray, offset ) {
  263. this.bind();
  264. this.setValue( sourceArray, offset );
  265. },
  266. // create getter / setter pair for a property in the scene graph
  267. bind: function () {
  268. var targetObject = this.node,
  269. parsedPath = this.parsedPath,
  270. objectName = parsedPath.objectName,
  271. propertyName = parsedPath.propertyName,
  272. propertyIndex = parsedPath.propertyIndex;
  273. if ( ! targetObject ) {
  274. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  275. this.node = targetObject;
  276. }
  277. // set fail state so we can just 'return' on error
  278. this.getValue = this._getValue_unavailable;
  279. this.setValue = this._setValue_unavailable;
  280. // ensure there is a value node
  281. if ( ! targetObject ) {
  282. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  283. return;
  284. }
  285. if ( objectName ) {
  286. var objectIndex = parsedPath.objectIndex;
  287. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  288. switch ( objectName ) {
  289. case 'materials':
  290. if ( ! targetObject.material ) {
  291. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  292. return;
  293. }
  294. if ( ! targetObject.material.materials ) {
  295. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  296. return;
  297. }
  298. targetObject = targetObject.material.materials;
  299. break;
  300. case 'bones':
  301. if ( ! targetObject.skeleton ) {
  302. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  303. return;
  304. }
  305. // potential future optimization: skip this if propertyIndex is already an integer
  306. // and convert the integer string to a true integer.
  307. targetObject = targetObject.skeleton.bones;
  308. // support resolving morphTarget names into indices.
  309. for ( var i = 0; i < targetObject.length; i ++ ) {
  310. if ( targetObject[ i ].name === objectIndex ) {
  311. objectIndex = i;
  312. break;
  313. }
  314. }
  315. break;
  316. default:
  317. if ( targetObject[ objectName ] === undefined ) {
  318. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  319. return;
  320. }
  321. targetObject = targetObject[ objectName ];
  322. }
  323. if ( objectIndex !== undefined ) {
  324. if ( targetObject[ objectIndex ] === undefined ) {
  325. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  326. return;
  327. }
  328. targetObject = targetObject[ objectIndex ];
  329. }
  330. }
  331. // resolve property
  332. var nodeProperty = targetObject[ propertyName ];
  333. if ( nodeProperty === undefined ) {
  334. var nodeName = parsedPath.nodeName;
  335. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  336. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  337. return;
  338. }
  339. // determine versioning scheme
  340. var versioning = this.Versioning.None;
  341. this.targetObject = targetObject;
  342. if ( targetObject.needsUpdate !== undefined ) { // material
  343. versioning = this.Versioning.NeedsUpdate;
  344. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  345. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  346. }
  347. // determine how the property gets bound
  348. var bindingType = this.BindingType.Direct;
  349. if ( propertyIndex !== undefined ) {
  350. // access a sub element of the property array (only primitives are supported right now)
  351. if ( propertyName === "morphTargetInfluences" ) {
  352. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  353. // support resolving morphTarget names into indices.
  354. if ( ! targetObject.geometry ) {
  355. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  356. return;
  357. }
  358. if ( targetObject.geometry.isBufferGeometry ) {
  359. if ( ! targetObject.geometry.morphAttributes ) {
  360. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  361. return;
  362. }
  363. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  364. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  365. propertyIndex = i;
  366. break;
  367. }
  368. }
  369. } else {
  370. if ( ! targetObject.geometry.morphTargets ) {
  371. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  372. return;
  373. }
  374. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  375. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  376. propertyIndex = i;
  377. break;
  378. }
  379. }
  380. }
  381. }
  382. bindingType = this.BindingType.ArrayElement;
  383. this.resolvedProperty = nodeProperty;
  384. this.propertyIndex = propertyIndex;
  385. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  386. // must use copy for Object3D.Euler/Quaternion
  387. bindingType = this.BindingType.HasFromToArray;
  388. this.resolvedProperty = nodeProperty;
  389. } else if ( Array.isArray( nodeProperty ) ) {
  390. bindingType = this.BindingType.EntireArray;
  391. this.resolvedProperty = nodeProperty;
  392. } else {
  393. this.propertyName = propertyName;
  394. }
  395. // select getter / setter
  396. this.getValue = this.GetterByBindingType[ bindingType ];
  397. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  398. },
  399. unbind: function () {
  400. this.node = null;
  401. // back to the prototype version of getValue / setValue
  402. // note: avoiding to mutate the shape of 'this' via 'delete'
  403. this.getValue = this._getValue_unbound;
  404. this.setValue = this._setValue_unbound;
  405. }
  406. } );
  407. //!\ DECLARE ALIAS AFTER assign prototype !
  408. Object.assign( PropertyBinding.prototype, {
  409. // initial state of these methods that calls 'bind'
  410. _getValue_unbound: PropertyBinding.prototype.getValue,
  411. _setValue_unbound: PropertyBinding.prototype.setValue,
  412. } );
  413. export { PropertyBinding };