Forum

User posts Kirill Osipov
02 February 2016 16:29
в плеере бленда отображать опцию
Не могли бы вы подробнее разъяснить, что имеете в виду.

Функционал "осмотр при помощи гироскопа" будет реализован в аддоне gyroscope.js. Поэтому для его активации пользователю потребуется в своем приложении вызвать функцию enable_camera_rotation. Скорее всего, API данного модуля будет изменено в ближайшем релизе.

Здесь я описал приблизительный код, который может вам пригодится.
Blend4Web Team
kirill@blend4web.com
02 February 2016 16:14

В математических преобразованиях такого типа пока что не силён…
Написал пример, будет возможность проверьте пожалуйста.

//...
var m_cam = require("camera");
var m_ctl = require("controls");
var m_quat = require("quat");
var m_scenes = require("scenes");
var m_trans = require("transform");
var m_util = require("util");
var m_vec3  = require("vec3");

var _last_gyro_quat = m_quat.create();

var _quat_tmp = m_quat.create();
var _quat_tmp2 = m_quat.create();
var _vec3_tmp = m_vec3.create();
// ...
function create_rotation_sensors() {
    var obj = m_scenes.get_active_camera();
    var g_sensor = m_ctl.create_gyro_angles_sensor();
    var save_angles = true;

    var rotate_cb = function(obj, id, pulse) {
        if (pulse > 0) {

            var curr_angles = m_ctl.get_sensor_payload(obj, id, 0);
            if (m_cam.is_eye_camera(obj)) {
                var alpha = curr_angles[2];
                var beta  = curr_angles[1];
                var gamma = curr_angles[0];

                // 1) По углам alpha, beta, gamma построить кватернион поворота устройств (значение из датчиков).
                // http://w3c.github.io/deviceorientation/spec-source-orientation.html
                var quaternion = _quat_tmp;
                var c1 = Math.cos(alpha / 2);
                var c2 = Math.cos(beta  / 2);
                var c3 = Math.cos(gamma / 2);
                var s1 = Math.sin(alpha / 2);
                var s2 = Math.sin(beta  / 2);
                var s3 = Math.sin(gamma / 2);
                quaternion[0] = c1 * s2 * c3 - s1 * c2 * s3;
                quaternion[1] = c1 * c2 * s3 + s1 * s2 * c3;
                quaternion[2] = s1 * c2 * c3 + c1 * s2 * s3;
                quaternion[3] = c1 * c2 * c3 - s1 * s2 * s3;

                // 2) Построить кватернион ориентации устройства (взять угол windows.orientation)
                var orientation = Math.PI * window.orientation / 180;
                var screen_quat = m_quat.setAxisAngle(m_util.AXIS_Z,
                        -orientation, _quat_tmp2);

                // 3) Умножить кватернион из 1) на кватернион из 2)
                quaternion = m_quat.multiply(quaternion, screen_quat, _quat_tmp);

                // 4) Взять кватернион поворота на угол Math.PI/2 вокруг оси OX (переход в мировую систему координат в движке)
                var quat = m_quat.setAxisAngle(m_util.AXIS_X, Math.PI / 2,
                        _quat_tmp2);
                // 5) Умножить кватернион из 3) на кватернион из 4)
                quaternion = m_quat.multiply(quaternion, quat, _quat_tmp);

                // Дальше устанавливаем поведение, пусть будет работать гироскоп и touch
                if (save_angles) {
                    m_quat.copy(quaternion, _last_gyro_quat);
                    save_angles = false;
                } else {
                    var last_gyro_inv_quat = m_quat.invert(_last_gyro_quat, _last_gyro_quat);
                    var cam_quat = m_trans.get_rotation(obj, _quat_tmp2);
                    var clear_cam_quat = m_quat.multiply(cam_quat, last_gyro_inv_quat, _quat_tmp2);
                    var new_cam_quat = m_quat.multiply(clear_cam_quat, quaternion, _quat_tmp2);

                    var up_axis = m_vec3.transformQuat(m_util.AXIS_MZ,
                            new_cam_quat, _vec3_tmp);
                     // 7) Установить вертикальную ось для камеры (функция camera.set_vertical_axis добавлена в версии 16.01 движка).
                    m_cam.set_vertical_axis(obj, up_axis);
                    // 6) Установить для объекта камеры кватернион поворота
                    m_trans.set_rotation_v(obj, new_cam_quat);
                    m_quat.copy(quaternion, _last_gyro_quat);
                }
            }
        }
    }
    m_ctl.create_sensor_manifold(obj, "ROTATE_GYRO", 
            m_ctl.CT_CONTINUOUS, [g_sensor], null, rotate_cb);
}

};
Blend4Web Team
kirill@blend4web.com
30 January 2016 15:07
Кстати, забыл сказать, в движке имеется уже аддон gyroscope.js. Его функционирование можно понаблюдать в приложении viewer, активировав флаг на соответствующей панели (gyroscope).
Blend4Web Team
kirill@blend4web.com
30 January 2016 14:29
Есть несколько способов это сделать. Но я бы посоветовал использовать кватернионы. Однако, возможно, в API будет функция позволяющая уставнавлить поворот по трём углам.

А пока предлагаю следующее решение.
1) По углам alpha, beta, gamma построить кватернион поворота устройств (значение из датчиков).
2) Построить кватернион ориентации устройства (взять угол windows.orientation)
3) Умножить кватернион из 1) на кватернион из 2)
4) Взять кватернион поворота на угол Math.PI/2 вокруг оси OX (переход в мировую систему координат в движке)
5) Умножить кватернион из 3) на кватернион из 4)
6) Установить для объекта камеры кватернион поворота из пункта 5) (функция trans.set_rotation_v)
7) Установить вертикальную ось для камеры (функция camera.set_vertical_axis добавлена в версии 16.01 движка).
Например,
var up_axis = m_vec3.transformQuat(m_util.AXIS_Z,
result_quat, _vec3_tmp);
m_cam.set_vertical_axis(camobj, up_axis);

Возможно, мною было что-то упущено, но общая схема приблизительно такова. Подробнее можно прочитать здесь

Скорее всего, данный функционал будет реализован в src/addons/gyroscope.js в рамках поддержки виртуальной реальности для мобильных устройств.
Blend4Web Team
kirill@blend4web.com
21 January 2016 10:57
You can enable distortion (v15.12) for DK2.

m_scenes.set_hmd_params({
enable_hmd_stereo: true,
distortion_scale: 0.666,
distortion_coefs: [0.22, 0.28]
})

But it does not correcting chromatic aberration (webvr-boilerplate does same).

I'm thinking I can save whatever that is for the dk2 and use that for the time being.
In case of using engine distortion it is better to disable browser distortion.
requestFullScreen({"vrDistortion": false});


Right correction requires right distortion coefficients.
For example,
OculusRiftDK2 — [0.22, 0.28]
CardboardV1 — [0.441, 0.156]
CardboardV2 — [0.34, 0.55]
Blend4Web Team
kirill@blend4web.com
20 January 2016 23:21
This gives the same error
Try:
b4w.register("riftTest", function(exports, require) {
// …
var m_cfg = require("config");
var m_scenes = require("scenes");
// …
exports.init = function() {
// …
m_cfg.set("stereo", "HMD");
// …
}
// …
function load_cb(data_id) {
// …
m_scenes.set_hmd_params({enable_hmd_stereo: true, distortion_scale: 1})
// …
}

}
window.addEventListener("load", function() {b4w.require("riftTest").init();});


It works for me. It is better to call container.resize after scenes.set_hmd_params
Here is the example, it was created with using the project manager.
Blend4Web Team
kirill@blend4web.com
20 January 2016 23:05
This gives the same error
Hm… It seems like a bug.

P.S. Is there a date for this?
Around next week
Blend4Web Team
kirill@blend4web.com
20 January 2016 22:32
I'm assuming this works when WebVR is working properly.

Browser does not distoriton correction without WebVR
Only Brandon's Chromium build does distortion stuff right now.
Blend4Web Team
kirill@blend4web.com
20 January 2016 22:21
Comming version (16.01) of the engine fixes many rendering issues.

I'm using OpenHMD with a python wrapper to get the tracking data which eventually gets sent over a websocket. I can then read this data using JS. It sounds a little "round about" ish but I need to go this route for my application.

Hhmm. I think it is a good decision.

I tried doing this and it did not create a side by side image. Where in the .js file should I set these properties (I tried it in the load_cb and I get
It is my fault. You need to do something like this:
// …
var m_scenes = require("scenes");
// …
var hmd_params = {};
hmd_params.enable_hmd_stereo = true;
m_scenes.set_hmd_params(hmd_params);
// …

I can check the code only tomorrow :-(, but you can try.

Finally, the stereo.glslf file alludes to distortion for HMDs. Is this experimental/not yet working?
Hehe, yes, it does not work right yet.

Can I use the distortion specific part even if the Rift runtime is not available or a device is not connected?
You can set up VR rendering mode (a side by side image) without connected device.
Blend4Web Team
kirill@blend4web.com
20 January 2016 21:04
Hello jansoft88 and welcome to our forum.

Ответ на сообщение пользователя jansoft88
All I need is the ability to generate the side by side image with the proper distortion. Is there a way to achieve the HMD post processing effect without using WebVR?

Main purpose of WebVR API is to get sensors data. There is not another way get tracking data in browser (or I just don't know another way).

Engine solves many issues.
1. It generates the side by side image, use set_hmd_params({enable_hmd_stereo: true}) to enable this rendering mode.
2. Set orientation behavior of a camera.
3. Distortion is in our TODO. But experimental build of Chromium does the distortion by default.
"It's highly recommended that you let the browser do the distortion for you."(Brandon Jones)

1. I am using Linux and support from Oculus is currently "on-pause".
Yes, unfortunately, we are using source code older version right now. There is only way to get tracking data in browser.

2. I need the tracking data to be read by (and possibly manipulated by) another program before it reaches Blend4Web.
You can disable default camera behavior (just does not call enable_hmd), and set up your own behavior.
Blend4Web Team
kirill@blend4web.com