babylon.pointerDragBehavior.ts 16 KB

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