From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/fr/web/api/webvr_api/index.html | 148 ++++++++++++ .../index.html" | 257 +++++++++++++++++++++ 2 files changed, 405 insertions(+) create mode 100644 files/fr/web/api/webvr_api/index.html create mode 100644 "files/fr/web/api/webvr_api/utiliser_des_contr\303\264leurs_de_realite_virtuelle_pour_du_webvr/index.html" (limited to 'files/fr/web/api/webvr_api') diff --git a/files/fr/web/api/webvr_api/index.html b/files/fr/web/api/webvr_api/index.html new file mode 100644 index 0000000000..a23eac2f67 --- /dev/null +++ b/files/fr/web/api/webvr_api/index.html @@ -0,0 +1,148 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +translation_of: Web/API/WebVR_API +--- +
{{draft("Attention, la traduction de cette page n'est pas terminée. De plus, la documentation de l'API WebVR est en cours de mise à jour pour couvrir la version v1.0, par conséquent certaines des ses informations vont être obsolètes. Contactez ~~chrisdavidmills si vous avez des questions à propos de cette documentation.")}}{{DefaultAPISidebar("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR fournit un support pour les dispositifs de réalité virtuelle - par exemple pour les casques de réalité virtuelle comme l'Oculus Rift - aux applications Web, permettant aux développeurs de traduire les informations de position et de mouvement de l'appareil en mouvements autour d'une scène 3D. Cela a de nombreuses applications très intéressantes, des visites de produits virtuels aux applications de formation interactive en passant par des jeux en première personne dans un environnement immersif.

+ +

Concepts et usage

+ +

Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"

+ +

Tous les périphériques de réalité virtuelle connectés à votre ordinateur seront donné grâce à la méthode {{domxref("Navigator.getVRDisplays()")}}. Cela retournera un tableau d'objets représentant les périphériques, qui auront l'héritage de l'objet {{domxref("VRDevice")}} — généralement un casque de réalité virtuelle renverra deux périphériques — le casque lui-même, représenté par {{domxref("HMDVRDevice")}}, et la caméra capteur de position qui suit la position de votre tête, représenté par {{domxref("PositionSensorVRDevice")}}.

+ +

L'objet {{domxref("PositionSensorVRDevice")}} contient la méthode {{domxref("PositionSensorVRDevice.getState","getState()")}}, qui retourne un objet {{domxref("VRPositionState")}} — cela représente l'état du capteur à un timecode donné, et inclus les propriétés avec des données utiles tel que la vélocité, l'accélération et l'orientation, utiles pour mettre à jour le rendu de la scène pour chaque image en accord avec le mouvement du casque de réalité virtuelle.

+ +

La méthode {{domxref("HMDVRDevice.getEyeParameters()")}} retourne un objet {{domxref("VREyeParameters")}}, qui peut être utilisé pour obtenir l'information du champ de vision — combien le casque de réalité virtuel peut afficher de la scène. Le {{domxref("VREyeParameters.currentFieldOfView")}} retourne un objet {{domxref("VRFieldOfView")}} qui contient quatre angles décrivant le champ de vision actuel depuis le point central. Vous pouvez aussi changer le champ de vision en utilisant {{domxref("HMDVRDevice.setFieldOfView()")}}.

+ +

Interfaces WebVR

+ +
+
{{domxref("VRDisplay")}}
+
Représente un périphérique de réalité virtuelle supporté par cette API. Il inclut des informations générales comme les IDs et des descriptions de l'appareil, ainsi que des méthodes pour commencer à présenter une scène RV, récupérer les paramètres visuels, les capacités d'affichage et d'autres fonctionnalités importantes.
+
{{domxref("VRDisplayCapabilities")}}
+
Décrit les capacités d'un appareil {{domxref("VRDisplay")}} — ses fonctionalités peuvent être utilisée pour tester les capacités du périphérique, par exemple peut-il retourner l'information de position.
+
{{domxref("VRPose")}}
+
Représente l'état de la position à un timecode donné (qui inclut l'orientation, la position, la vélocité et l'accélération).
+
{{domxref("VREyeParameters")}}
+
Donne accès à l'ensemble des informations requises pour faire le rendu d'une scène pour l'oeil indiqué, dont les informations de champ de vision.
+
{{domxref("VRFieldOfView")}}
+
Représente le champ de vision actuel définit par quatre angles décrivant la vue depuis le point central.
+
{{domxref("VRLayer")}}
+
Représente un calque d'un objet {{domxref("VRDisplay")}}.
+
{{domxref("VRStageParameters")}}
+
Représente les données décrivant l'espace physique disponible pour les périphériques de réalité virtuelle pouvant offrir une expérience dans une pièce réelle.
+
+ +

Extensions à d'autres interfaces

+ +
+
{{domxref("Gamepad.displayId")}} {{readonlyInline}}
+
Retourne l'ID {{domxref("VRDisplay.displayId")}} du périphérique {{domxref("VRDisplay")}} associé — l'appareil RV où la manette de jeu contrôle la scene affichée.
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}
+
Retourne un tableau contenant tous les périphériques (objet {{domxref("VRDisplay")}}) qui sont actifs (quand {{domxref("VRDisplay.ispresenting")}} est à true).
+
{{domxref("Navigator.getVRDisplays()")}}
+
Retourne un tableau contenant tous les périphériques (objet {{domxref("VRDisplay")}}) disponibles qui sont connectés à l'ordinateur.
+
{{domxref("Window.onvrdisplayconnected")}}
+
Représente un gestionaire d'événements qui s'exécute lorsqu'un appareil RV compatible a été connecté à l'ordinateur (quand l'événement {{event("vrdisplayconnected")}} est déclenché).
+
{{domxref("Window.onvrdisplaydisconnected")}}
+
Représente un gestionaire d'événements qui s'exécute lorsqu'un appareil RV compatible a été déconnecté de l'ordinateur  (quand l'événement {{event("vrdisplaydisconnected")}} est déclenché).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
Représente un gestionaire d'événements qui s'exécute lorsque l'état de présentation d'un appareil change — i.e. un changement de l'état "présente" à "ne présente pas", ou vice versa (quand l'événement {{event("onvrdisplaypresentchange")}} est déclenché).
+
+ +

Examples

+ +

Vous pouvez retrouver plusieurs exemples dans ces repos Github:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR')}}{{Spec2('WebVR')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for AndroidSamsung Internet for GearVR
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+  
+
+ +

See also

+ + diff --git "a/files/fr/web/api/webvr_api/utiliser_des_contr\303\264leurs_de_realite_virtuelle_pour_du_webvr/index.html" "b/files/fr/web/api/webvr_api/utiliser_des_contr\303\264leurs_de_realite_virtuelle_pour_du_webvr/index.html" new file mode 100644 index 0000000000..36b68601ff --- /dev/null +++ "b/files/fr/web/api/webvr_api/utiliser_des_contr\303\264leurs_de_realite_virtuelle_pour_du_webvr/index.html" @@ -0,0 +1,257 @@ +--- +title: Utiliser des contrôleurs de réalité virtuelle pour du WebVR +slug: Web/API/WebVR_API/Utiliser_des_contrôleurs_de_realite_virtuelle_pour_du_WebVR +translation_of: Web/API/WebVR_API/Using_VR_controllers_with_WebVR +--- +
{{APIRef("WebVR API")}}
+ +

La plupart des matériels de WebVR possède des contrôleurs qui viennent avec le casque de réalité virtuelle. Ceux-ci peuvent être utilisés dans les application WebVR grâce à l'API Gamepad, et plus spécifiquement avec l'API Gamepad Extensions qui ajoute des API pour accéder, entre autres, à la position du controller, au retour haptique, etc.. Cet article fournit les bases pour utiliser ces API.

+ +

L'API WebVR

+ +

L'API WebVR est jeune mais possède déjà des fonctionnalités très interressantes pour le web et pour que les développeur·euse·s puisse créer des expériences de réalité virtuelle sur le web. Cela est possible grâce à un accès aux données des casques de réalité virtuelle connectés à votre ordinateur. Ceux-ci seront indentifié comme des objets {{domxref("VRDisplay")}},que vous pourrez manipuler pour commencer et arrêter l'affichage dans le casque, récupérer des données de mouvement (orientation, position...) qui pourront être utilisés pour mettre à jour l'affichage d'une animation, par exemple.

+ +

Avant de commencer, vous devriez être déjà avoir des bases de l'API WebVR. Si ce n'est pas le cas, allez lire l'article Utiliser l'API WebVR, vous aurez également des détails sur la compatibilité des navigateurs web ou du matériel nécessaire.

+ +

L'API Gamepad

+ +

L'API Gamepad est une API assez bien compatible, qui donne aux développeur·euse·s l'accès aux manettes de jeu, connectés à leur ordinateur et de les utilisé dans dans applications web. Les contrôleurs peuvent basiquement être accessible comme des objets {{domxref("Gamepad")}}, avec lesquels nous pouvons faire des requêtes pour savoir quels boutons sont appuyés ou quels joystick sont actionnés, etc..

+ +

Vous pouvez avoir plus d'information sur l'usage de API de base des Gamepad avec l'article Utilisez l'API Gamepad, et Implementer des contrôles en utilisant l'API Gamepad.

+ +

Dans cet article, nous allons nous attardez sur les nouvelles fonctionnalités offertes dans l'API {{specname("GamepadExtensions")}}, laquelle donne accès à des informations avancés comme des données de position ou d'orientation, ou encore contrôler les retours haptiques (vibrations), et bien plus. Cette API est toute nouvelle et, pour l'instant, seulement disponible dans les versions Beta ou Nightly de Firefox 55 (et suppérieur).

+ +

Types de contrôlleurs

+ +

Il y a deux principaux types de contrôleurs utilisés pour la réalité virtuelle :

+ + + +

Basic controller access

+ +

Now onto some code. Let's look first at the basics of how we get access to VR controllers with the Gamepad API. There are a few strange nuances to bear in mind here, so it is worth taking a look.

+ +

We've written up a simple example to demonstrate — see our vr-controller-basic-info source code (see it running live here also). This demo simply outputs information on the VR displays and gamepads connected to your computer.

+ +

Getting the display information

+ +

The first notable code is as follows:

+ +
var initialRun = true;
+
+if(navigator.getVRDisplays && navigator.getGamepads) {
+  info.textContent = 'WebVR API and Gamepad API supported.'
+  reportDisplays();
+} else {
+  info.textContent = 'WebVR API and/or Gamepad API not supported by this browser.'
+}
+ +

Here we first use a tracking variable, initialRun, to note that this is the first time we have loaded the page. You'll find out more about this later on. Next, we detect to see if the WebVR and Gamepad APIs are supported by cheking for the existence of the {{domxref("Navigator.getVRDisplays()")}} and {{domxref("Navigator.getGamepads()")}} methods. If so, we run our reportDisplays() custom function to start the process off. This function looks like so:

+ +
function reportDisplays() {
+  navigator.getVRDisplays().then(function(displays) {
+      console.log(displays.length + ' displays');
+    for(var i = 0; i < displays.length; i++) {
+      var cap = displays[i].capabilities;
+      // cap is a VRDisplayCapabilities object
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>Display ' + (i+1) + '</strong>'
+                   + '<br>VR Display ID: ' + displays[i].displayId
+                   + '<br>VR Display Name: ' + displays[i].displayName
+                   + '<br>Display can present content: ' + cap.canPresent
+                   + '<br>Display is separate from the computer\'s main display: ' + cap.hasExternalDisplay
+                   + '<br>Display can return position info: ' + cap.hasPosition
+                   + '<br>Display can return orientation info: ' + cap.hasOrientation
+                   + '<br>Display max layers: ' + cap.maxLayers;
+      list.appendChild(listItem);
+    }
+
+    setTimeout(reportGamepads, 1000);
+    // For VR, controllers will only be active after their corresponding headset is active
+  });
+}
+ +

This function first uses the promise-based {{domxref("Navigator.getVRDisplays()")}} method, which resolves with an array containing {{domxref("VRDisplay")}} objects representing the connected displays. Next, it prints out each display's {{domxref("VRDisplay.displayId")}} and {{domxref("VRDisplay.displayName")}} values, and a number of useful values contained in the display's associated {{domxref("VRCapabilities")}} object. The most useful of these are {{domxref("VRCapabilities.hasOrientation","hasOrientation")}} and {{domxref("VRCapabilities.hasPosition","hasPosition")}}, which allow you to detect whether the device can return orientation and position data and set up your app accordingly.

+ +

The last line contained in this function is a {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}} call, which runs the reportGamepads() function after a 1 second delay. Why do we need to do this? First of all, VR controllers will only be ready after their associated VR headset is active, so we need to invoke this after getVRDisplays() has been called and returned the display information. Second, the Gamepad API is much older than the WebVR API, and not promise-based. As you'll see later, the getGamepads() method is synchronous, and just returns the Gamepad objects immediately — it doesn't wait for the controller to be ready to report information. Unless you wait for a little while, returned information may not be accurate (at least, this is what we found in our tests).

+ +

Getting the Gamepad information

+ +

The reportGamepads() function looks like this:

+ +
function reportGamepads() {
+    var gamepads = navigator.getGamepads();
+    console.log(gamepads.length + ' controllers');
+    for(var i = 0; i < gamepads.length; ++i) {
+        var gp = gamepads[i];
+    var listItem = document.createElement('li');
+    listItem.classList = 'gamepad';
+    listItem.innerHTML = '<strong>Gamepad ' + gp.index + '</strong> (' + gp.id + ')'
+                 + '<br>Associated with VR Display ID: ' + gp.displayId
+                 + '<br>Gamepad associated with which hand: ' + gp.hand
+                 + '<br>Available haptic actuators: ' + gp.hapticActuators.length
+                 + '<br>Gamepad can return position info: ' + gp.pose.hasPosition
+                 + '<br>Gamepad can return orientation info: ' + gp.pose.hasOrientation;
+    list.appendChild(listItem);
+  }
+  initialRun = false;
+}
+ +

This works in a similar manner to reportDisplays() — we get an array of {{domxref("Gamepad")}} objects using the non-promise-based getGamepads() method, then cycle through each one and print out information on each:

+ + + +

Note that we also gave each list item containing controller information a class name of gamepad. We'll explain what this is for later.

+ +

The last thing to do here is set the initialRun variable to false, as the initial run is now over.

+ +

Gamepad events

+ +

To finish off this section, we'll look at the gamepad-associated events. There are two we need concern ourselves with — {{event("gamepadconnected")}} and {{event("gamepaddisconnected")}} — and it is fairly obvious what they do.

+ +

At the end of our example we first include the removeGamepads() function:

+ +
function removeGamepads() {
+    var gpLi = document.querySelectorAll('.gamepad');
+    for(var i = 0; i < gpLi.length; i++) {
+    list.removeChild(gpLi[i]);
+    }
+
+    reportGamepads();
+}
+ +

This function simply grabs references to all list items with a class name of gamepad, and removes them from the DOM. Then it re-runs reportGamepads() to populate the list with the updated list of connected controllers.

+ +

removeGamepads() will be run each time a gamepad is connected or disconnected, via the following event handlers:

+ +
window.addEventListener('gamepadconnected', function(e) {
+  info.textContent = 'Gamepad ' + e.gamepad.index + ' connected.';
+  if(!initialRun) {
+      setTimeout(removeGamepads, 1000);
+  }
+});
+
+window.addEventListener('gamepaddisconnected', function(e) {
+  info.textContent = 'Gamepad ' + e.gamepad.index + ' disconnected.';
+  setTimeout(removeGamepads, 1000);
+});
+ +

We have setTimeout() calls in place here — like we did with the initialization code at the top of the script — to make sure that the gamepads are ready to report their information when reportGamepads() is called in each case.

+ +

But there's one more thing to note — you'll see that inside the gamepadconnected handler, the timeout is only run if initialRun is false. This is because if your gamepads are connected when the document first loads, gamepadconnected is fired once for each gamepad, therefore removeGamepads()/reportGamepads() will be run several times. This could lead to inaccurate results, therefore we only want to run removeGamepads() inside the gamepadconnected handler after the initial run, not during it. This is what initialRun is for.

+ +

Introducing a real demo

+ +

Now let's look at the Gamepad API being used inside a real WebVR demo. You can find this demo at raw-webgl-controller-example (see it live here also).

+ +

In exactly the same way as our raw-webgl-example (see Using the WebVR API for details), this renders a spinning 3D cube, which you can choose to present in a VR display. The only difference is that, while in VR presenting mode, this demo allows you to move the cube by moving a VR controller (the original demo moves the cube as you move your VR headset).

+ +

We'll explore the code differences in this version below — see webgl-demo.js.

+ +

Accessing the gamepad data

+ +

Inside the drawVRScene() function, you'll find this bit of code:

+ +
var gamepads = navigator.getGamepads();
+var gp = gamepads[0];
+
+if(gp) {
+  var gpPose = gp.pose;
+  var curPos = gpPose.position;
+  var curOrient = gpPose.orientation;
+  if(poseStatsDisplayed) {
+    displayPoseStats(gpPose);
+  }
+}
+ +

Here we get the connected gamepads with {{domxref("Navigator.getGamepads")}}, then store the first gamepad detected in the gp variable. As we only need one gamepad for this demo, we'll just ignore the others.

+ +

The next thing we do is to get the {{domxref("GamepadPose")}} object for the controller stored in gpPose (by querying {{domxref("Gamepad.pose")}}), and also store the current gamepad position and orientation for this frame in variables so they are easuy to access later. We also display the post stats for this frame in the DOM using the displayPoseStats() function. All of this is only done if gp actually has a value (if a gamepad is connected), which stops the demo erroring if we don't have our gamepad connected.

+ +

Slightly later in the code, you can find this block:

+ +
if(gp && gpPose.hasPosition) {
+  mvTranslate([
+                0.0 + (curPos[0] * 15) - (curOrient[1] * 15),
+                0.0 + (curPos[1] * 15) + (curOrient[0] * 15),
+                -15.0 + (curPos[2] * 25)
+             ]);
+} else if(gp) {
+  mvTranslate([
+                0.0 + (curOrient[1] * 15),
+                0.0 + (curOrient[0] * 15),
+                -15.0
+             ]);
+} else {
+  mvTranslate([
+                0.0,
+                0.0,
+                -15.0
+             ]);
+}
+ +

Here we alter the position of the cube on the screen according to the {{domxref("GamepadPose.position","position")}} and {{domxref("GamepadPose.orientation","orientation")}} data received from the connected controller. These values (stored in curPos and curOrient) are {{domxref("Float32Array")}}s containing the X, Y, and Z values (here we are just using [0] which is X, and [1] which is Y).

+ +

If the gp variable has a Gamepad object inside it and it can return position values (gpPose.hasPosition), indicating a 6DoF controller, we modify the cube position using position and orientation values. If only the former is true, indicating a 3DoF controller, we modify the cube position using the orientation values only. If there is no gamepad connected, we don't modify the cube position at all.

+ +

Displaying the gamepad pose data

+ +

In the displayPoseStats() function, we grab all of the data we want to display out of the {{domxref("GamepadPose")}} object passed into it, then print them into the UI panel that exists in the demo for displaying such data:

+ +
function displayPoseStats(pose) {
+  var pos = pose.position;
+  var orient = pose.orientation;
+  var linVel = pose.linearVelocity;
+  var linAcc = pose.linearAcceleration;
+  var angVel = pose.angularVelocity;
+  var angAcc = pose.angularAcceleration;
+
+  if(pose.hasPosition) {
+    posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3);
+  } else {
+    posStats.textContent = 'Position not reported';
+  }
+
+  if(pose.hasOrientation) {
+    orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3);
+  } else {
+    orientStats.textContent = 'Orientation not reported';
+  }
+
+  linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3);
+  angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3);
+
+  if(linAcc) {
+    linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3);
+  } else {
+    linAccStats.textContent = 'Linear acceleration not reported';
+  }
+
+  if(angAcc) {
+    angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3);
+  } else {
+    angAccStats.textContent = 'Angular acceleration not reported';
+  }
+}
+ +

Summary

+ +

This article has given you a very basic idea of how to use the Gamepad Extensions to use VR controllers inside WebVR apps. In a real app you'd probably have a much more complex control system in effect, with controls assigned to the buttons on the VR controllers, and the display being affected by both the display pose and the controller poses simultaneously. Here however, we just wanted to isolate the pure Gamepad Extensions parts of that.

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf