babylon.pointerDragBehavior.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. module BABYLON {
  2. /**
  3. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  4. */
  5. export class PointerDragBehavior implements Behavior<Mesh> {
  6. private _attachedNode: Node;
  7. private _dragPlane: Mesh;
  8. private _scene:Scene;
  9. private _pointerObserver:Nullable<Observer<PointerInfo>>;
  10. private static _planeScene:Scene;
  11. /**
  12. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  13. */
  14. public currentDraggingPointerID = -1;
  15. /**
  16. * The last position where the pointer hit the drag plane in world space
  17. */
  18. public lastDragPosition:Vector3;
  19. /**
  20. * If the behavior is currently in a dragging state
  21. */
  22. public dragging = false;
  23. /**
  24. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  25. */
  26. public dragDeltaRatio = 0.2;
  27. /**
  28. * If the drag plane orientation should be updated during the dragging (Default: true)
  29. */
  30. public updateDragPlane = true;
  31. // Debug mode will display drag planes to help visualize behavior
  32. private _debugMode = false;
  33. private _moving = false;
  34. /**
  35. * Fires each time the attached mesh is dragged with the pointer
  36. * * delta between last drag position and current drag position in world space
  37. * * dragDistance along the drag axis
  38. * * dragPlaneNormal normal of the current drag plane used during the drag
  39. * * dragPlanePoint in world space where the drag intersects the drag plane
  40. */
  41. public onDragObservable = new Observable<{delta:Vector3, dragPlanePoint:Vector3, dragPlaneNormal:Vector3, dragDistance:number, pointerId:number}>()
  42. /**
  43. * Fires each time a drag begins (eg. mouse down on mesh)
  44. */
  45. public onDragStartObservable = new Observable<{dragPlanePoint:Vector3, pointerId:number}>()
  46. /**
  47. * Fires each time a drag ends (eg. mouse release after drag)
  48. */
  49. public onDragEndObservable = new Observable<{dragPlanePoint:Vector3, pointerId:number}>()
  50. /**
  51. * If the attached mesh should be moved when dragged
  52. */
  53. public moveAttached = true;
  54. /**
  55. * If the drag behavior will react to drag events (Default: true)
  56. */
  57. public enabled = true;
  58. /**
  59. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  60. */
  61. public useObjectOrienationForDragging = true;
  62. /**
  63. * Creates a pointer drag behavior that can be attached to a mesh
  64. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  65. */
  66. constructor(private options:{dragAxis?:Vector3, dragPlaneNormal?:Vector3}){
  67. var optionCount = 0;
  68. if(options === undefined){
  69. options = {}
  70. }
  71. if(options.dragAxis){
  72. optionCount++;
  73. }
  74. if(options.dragPlaneNormal){
  75. optionCount++;
  76. }
  77. if(optionCount > 1){
  78. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  79. }
  80. }
  81. /**
  82. * The name of the behavior
  83. */
  84. public get name(): string {
  85. return "PointerDrag";
  86. }
  87. /**
  88. * Initializes the behavior
  89. */
  90. public init() {}
  91. private _tmpVector = new Vector3(0,0,0);
  92. private _worldDragAxis = new Vector3(0,0,0);
  93. /**
  94. * Attaches the drag behavior the passed in mesh
  95. * @param ownerNode The mesh that will be dragged around once attached
  96. */
  97. public attach(ownerNode: Mesh): void {
  98. this._scene = ownerNode.getScene();
  99. this._attachedNode = ownerNode;
  100. // Initialize drag plane to not interfere with existing scene
  101. if(!PointerDragBehavior._planeScene){
  102. if(this._debugMode){
  103. PointerDragBehavior._planeScene = this._scene;
  104. }else{
  105. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  106. this._scene.getEngine().scenes.pop();
  107. }
  108. }
  109. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  110. // State of the drag
  111. this.lastDragPosition = new BABYLON.Vector3(0,0,0);
  112. var delta = new BABYLON.Vector3(0,0,0);
  113. var dragLength = 0;
  114. var targetPosition = new BABYLON.Vector3(0,0,0);
  115. var pickPredicate = (m:AbstractMesh)=>{
  116. return this._attachedNode == m || m.isDescendantOf(this._attachedNode)
  117. }
  118. this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo, eventState)=>{
  119. if(!this.enabled){
  120. return;
  121. }
  122. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  123. if(!this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)){
  124. this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  125. var pickedPoint = this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  126. if(pickedPoint){
  127. this.dragging = true;
  128. this.currentDraggingPointerID = (<PointerEvent>pointerInfo.event).pointerId;
  129. this.lastDragPosition.copyFrom(pickedPoint);
  130. this.onDragStartObservable.notifyObservers({dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID});
  131. targetPosition.copyFrom((<Mesh>this._attachedNode).absolutePosition)
  132. }
  133. }
  134. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP){
  135. if(this.currentDraggingPointerID == (<PointerEvent>pointerInfo.event).pointerId){
  136. this.releaseDrag();
  137. }
  138. }else if(pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE){
  139. if(this.currentDraggingPointerID == (<PointerEvent>pointerInfo.event).pointerId && this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray){
  140. this._moving = true;
  141. var pickedPoint = this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  142. if (pickedPoint) {
  143. if(this.updateDragPlane){
  144. this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  145. }
  146. // depending on the drag mode option drag accordingly
  147. if(this.options.dragAxis){
  148. // Convert local drag axis to world
  149. Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  150. // Project delta drag from the drag plane onto the drag axis
  151. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  152. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis)
  153. this._worldDragAxis.scaleToRef(dragLength, delta);
  154. }else{
  155. dragLength = delta.length();
  156. pickedPoint.subtractToRef(this.lastDragPosition, delta);
  157. }
  158. targetPosition.addInPlace(delta);
  159. this.onDragObservable.notifyObservers({dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID});
  160. this.lastDragPosition.copyFrom(pickedPoint);
  161. }
  162. }
  163. }
  164. });
  165. this._scene.onBeforeRenderObservable.add(()=>{
  166. if(this._moving && this.moveAttached){
  167. // Slowly move mesh to avoid jitter
  168. targetPosition.subtractToRef((<Mesh>this._attachedNode).absolutePosition, this._tmpVector);
  169. this._tmpVector.scaleInPlace(0.2);
  170. (<Mesh>this._attachedNode).getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector);
  171. (<Mesh>this._attachedNode).setAbsolutePosition(this._tmpVector);
  172. }
  173. });
  174. }
  175. public releaseDrag(){
  176. this.dragging = false;
  177. this.onDragEndObservable.notifyObservers({dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID});
  178. this.currentDraggingPointerID = -1;
  179. this._moving = false;
  180. }
  181. private _pickWithRayOnDragPlane(ray:Nullable<Ray>){
  182. if(!ray){
  183. return null;
  184. }
  185. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, (m)=>{return m == this._dragPlane})
  186. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  187. return pickResult.pickedPoint;
  188. }else{
  189. return null;
  190. }
  191. }
  192. // Variables to avoid instantiation in the below method
  193. private _pointA = new Vector3(0,0,0);
  194. private _pointB = new Vector3(0,0,0);
  195. private _pointC = new Vector3(0,0,0);
  196. private _lineA = new Vector3(0,0,0);
  197. private _lineB = new Vector3(0,0,0);
  198. private _localAxis = new Vector3(0,0,0);
  199. private _lookAt = new Vector3(0,0,0);
  200. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  201. private _updateDragPlanePosition(ray:Ray, dragPlanePosition:Vector3){
  202. this._pointA.copyFrom(dragPlanePosition);
  203. if(this.options.dragAxis){
  204. this.useObjectOrienationForDragging ? Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  205. // Calculate plane normal in direction of camera but perpendicular to drag axis
  206. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  207. ray.origin.subtractToRef(this._pointA, this._pointC)
  208. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  209. // Get perpendicular line from direction to camera and drag axis
  210. this._pointB.subtractToRef(this._pointA, this._lineA);
  211. this._pointC.subtractToRef(this._pointA, this._lineB);
  212. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  213. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  214. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  215. this._lookAt.normalize();
  216. this._dragPlane.position.copyFrom(this._pointA);
  217. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  218. this._dragPlane.lookAt(this._lookAt);
  219. }else if(this.options.dragPlaneNormal){
  220. this.useObjectOrienationForDragging ? Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  221. this._dragPlane.position.copyFrom(this._pointA);
  222. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  223. this._dragPlane.lookAt(this._lookAt);
  224. }else{
  225. this._dragPlane.position.copyFrom(this._pointA);
  226. this._dragPlane.lookAt(ray.origin);
  227. }
  228. this._dragPlane.computeWorldMatrix(true);
  229. }
  230. /**
  231. * Detaches the behavior from the mesh
  232. */
  233. public detach(): void {
  234. if(this._pointerObserver){
  235. this._scene.onPointerObservable.remove(this._pointerObserver);
  236. }
  237. }
  238. }
  239. }