1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/xr/xr_webgl_layer.h"
#include <algorithm>
#include <utility>
#include "base/numerics/safe_conversions.h"
#include "base/trace_event/trace_event.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/modules/webgl/webgl_framebuffer.h"
#include "third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h"
#include "third_party/blink/renderer/modules/xr/xr_frame_provider.h"
#include "third_party/blink/renderer/modules/xr/xr_session.h"
#include "third_party/blink/renderer/modules/xr/xr_system.h"
#include "third_party/blink/renderer/modules/xr/xr_utils.h"
#include "third_party/blink/renderer/modules/xr/xr_view.h"
#include "third_party/blink/renderer/modules/xr/xr_viewport.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/size_f.h"
namespace blink {
namespace {
const double kFramebufferMinScale = 0.2;
const uint32_t kCleanFrameWarningLimit = 5;
const char kCleanFrameWarning[] =
"Note: The XRSession has completed multiple animation frames without "
"drawing anything to the baseLayer's framebuffer, resulting in no visible "
"output.";
} // namespace
XRWebGLLayer* XRWebGLLayer::Create(XRSession* session,
const V8XRWebGLRenderingContext* context,
const XRWebGLLayerInit* initializer,
ExceptionState& exception_state) {
if (session->ended()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Cannot create an XRWebGLLayer for an "
"XRSession which has already ended.");
return nullptr;
}
WebGLRenderingContextBase* webgl_context =
webglRenderingContextBaseFromUnion(context);
if (webgl_context->isContextLost()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Cannot create an XRWebGLLayer with a "
"lost WebGL context.");
return nullptr;
}
if (session->immersive() && !webgl_context->IsXRCompatible()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"WebGL context must be marked as XR compatible in order to "
"use with an immersive XRSession");
return nullptr;
}
if (session->GraphicsApi() != XRGraphicsBinding::Api::kWebGL) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Cannot create an XRWebGLLayer with a "
"WebGPU-based XRSession.");
return nullptr;
}
// TODO(crbug.com/941753): In the future this should be communicated by the
// drawing buffer and indicate whether the depth buffers are being supplied to
// the XR compositor.
bool compositor_supports_depth_values = false;
bool want_ignore_depth_values = initializer->ignoreDepthValues();
if (want_ignore_depth_values) {
UseCounter::Count(session->GetExecutionContext(),
WebFeature::kWebXrIgnoreDepthValues);
}
// The ignoreDepthValues attribute of XRWebGLLayer may only be set to false if
// the compositor is actually making use of the depth values and the user did
// not set ignoreDepthValues to true explicitly.
bool ignore_depth_values =
!compositor_supports_depth_values || want_ignore_depth_values;
double framebuffer_scale = 1.0;
// Inline sessions don't go through the XR compositor, so they don't need to
// allocate a separate drawing buffer or expose a framebuffer.
if (!session->immersive()) {
return MakeGarbageCollected<XRWebGLLayer>(session, webgl_context, nullptr,
nullptr, framebuffer_scale,
ignore_depth_values);
}
const bool want_antialiasing =
initializer->antialias() && session->CanEnableAntiAliasing();
const bool want_depth_buffer = initializer->depth();
const bool want_stencil_buffer = initializer->stencil();
const bool want_alpha_channel = initializer->alpha();
// Allocate a drawing buffer to back the framebuffer if needed.
if (initializer->hasFramebufferScaleFactor()) {
UseCounter::Count(session->GetExecutionContext(),
WebFeature::kWebXrFramebufferScale);
// The max size will be either the native resolution or the default
// if that happens to be larger than the native res. (That can happen on
// desktop systems.)
double max_scale = std::max(session->NativeFramebufferScale(), 1.0);
// Clamp the developer-requested framebuffer size to ensure it's not too
// small to see or unreasonably large.
// TODO(bajones): Would be best to have the max value communicated from the
// service rather than limited to the native res.
framebuffer_scale = std::clamp(initializer->framebufferScaleFactor(),
kFramebufferMinScale, max_scale);
}
gfx::SizeF framebuffers_size = session->RecommendedFramebufferSize();
gfx::Size desired_size =
gfx::ToFlooredSize(gfx::ScaleSize(framebuffers_size, framebuffer_scale));
// Create an opaque WebGL Framebuffer
WebGLFramebuffer* framebuffer = WebGLFramebuffer::CreateOpaque(
webgl_context, want_depth_buffer, want_stencil_buffer);
scoped_refptr<XRWebGLDrawingBuffer> drawing_buffer =
XRWebGLDrawingBuffer::Create(webgl_context->GetDrawingBuffer(),
framebuffer->Object(), desired_size,
want_alpha_channel, want_depth_buffer,
want_stencil_buffer, want_antialiasing);
if (!drawing_buffer) {
exception_state.ThrowDOMException(DOMExceptionCode::kOperationError,
"Unable to create a framebuffer.");
return nullptr;
}
return MakeGarbageCollected<XRWebGLLayer>(
session, webgl_context, std::move(drawing_buffer), framebuffer,
framebuffer_scale, ignore_depth_values);
}
XRWebGLLayer::XRWebGLLayer(XRSession* session,
WebGLRenderingContextBase* webgl_context,
scoped_refptr<XRWebGLDrawingBuffer> drawing_buffer,
WebGLFramebuffer* framebuffer,
double framebuffer_scale,
bool ignore_depth_values)
: XRLayer(session),
webgl_context_(webgl_context),
framebuffer_(framebuffer),
framebuffer_scale_(framebuffer_scale),
ignore_depth_values_(ignore_depth_values) {
if (framebuffer) {
// Must have a drawing buffer for immersive sessions.
DCHECK(drawing_buffer);
drawing_buffer_ = std::move(drawing_buffer);
} else {
// Only inline sessions are allowed to have a null drawing buffer.
DCHECK(!session->immersive());
}
UpdateViewports();
}
XRWebGLLayer::~XRWebGLLayer() {
if (drawing_buffer_) {
drawing_buffer_->BeginDestruction();
}
}
uint32_t XRWebGLLayer::framebufferWidth() const {
if (drawing_buffer_) {
return drawing_buffer_->size().width();
}
return webgl_context_->drawingBufferWidth();
}
uint32_t XRWebGLLayer::framebufferHeight() const {
if (drawing_buffer_) {
return drawing_buffer_->size().height();
}
return webgl_context_->drawingBufferHeight();
}
bool XRWebGLLayer::antialias() const {
if (drawing_buffer_) {
return drawing_buffer_->antialias();
}
if (!webgl_context_->isContextLost()) {
return webgl_context_->GetDrawingBuffer()->Multisample();
}
return false;
}
XRViewport* XRWebGLLayer::getViewport(XRView* view) {
if (!view || view->session() != session())
return nullptr;
if (view->ViewData()->ApplyViewportScaleForFrame()) {
UpdateViewports();
}
// framebuffer_scale_ is the scale requested by the web developer when this
// layer was created. The session's recommended framebuffer scale is the scale
// requested by the XR runtime. Both scales must be applied to the viewport.
return view->Viewport(framebuffer_scale_ *
session()->RecommendedFramebufferScale());
}
XRViewport* XRWebGLLayer::GetViewportForEye(device::mojom::blink::XREye eye) {
if (viewports_dirty_)
UpdateViewports();
if (eye == device::mojom::blink::XREye::kRight)
return right_viewport_.Get();
// This code path also handles an eye of "none".
return left_viewport_.Get();
}
double XRWebGLLayer::getNativeFramebufferScaleFactor(XRSession* session) {
return session->NativeFramebufferScale();
}
void XRWebGLLayer::UpdateViewports() {
uint32_t framebuffer_width = framebufferWidth();
uint32_t framebuffer_height = framebufferHeight();
if (framebuffer_width == 0U || framebuffer_height == 0U) {
LOG_IF(ERROR, !webgl_context_->isContextLost())
<< __func__ << " Received width=" << framebuffer_width
<< " height=" << framebuffer_height << " without having lost context";
return;
}
viewports_dirty_ = false;
// When calculating the scaled viewport size, round down to integer value, but
// ensure that the value is nonzero and doesn't overflow. See
// https://immersive-web.github.io/webxr/#xrview-obtain-a-scaled-viewport
auto rounded = [](double v) {
return std::max(1, base::saturated_cast<int>(v));
};
if (session()->immersive()) {
// Calculate new sizes with optional viewport scale applied. This assumes
// that XRSession::views() returns views in matching order.
if (session()->StereoscopicViews()) {
// TODO(1275873): This technically works fine because the entire bounds is
// still sent to the XR process, but if there are more than two views,
// the terms "left" and "right" are not accurate. The entire bounds of
// all viewports should be sent instead.
double left_scale =
session()
->ViewDataForEye(device::mojom::blink::XREye::kLeft)
->CurrentViewportScale();
left_viewport_ = MakeGarbageCollected<XRViewport>(
0, 0, rounded(framebuffer_width * 0.5 * left_scale),
rounded(framebuffer_height * left_scale));
double right_scale =
session()
->ViewDataForEye(device::mojom::blink::XREye::kRight)
->CurrentViewportScale();
right_viewport_ = MakeGarbageCollected<XRViewport>(
framebuffer_width * 0.5, 0,
rounded(framebuffer_width * 0.5 * right_scale),
rounded(framebuffer_height * right_scale));
} else {
// Phone immersive AR only uses one viewport, but the second viewport is
// needed for the UpdateLayerBounds mojo call which currently expects
// exactly two views. This should be revisited as part of a refactor to
// handle a more general list of viewports, cf. https://crbug.com/928433.
double mono_scale =
session()
->ViewDataForEye(device::mojom::blink::XREye::kNone)
->CurrentViewportScale();
left_viewport_ = MakeGarbageCollected<XRViewport>(
0, 0, rounded(framebuffer_width * mono_scale),
rounded(framebuffer_height * mono_scale));
right_viewport_ = nullptr;
}
session()->xr()->frameProvider()->UpdateWebGLLayerViewports(this);
} else {
// Currently, only immersive sessions implement dynamic viewport scaling.
// Ignore the setting for non-immersive sessions, effectively treating
// the minimum viewport scale as 1.0 which disables the feature.
left_viewport_ = MakeGarbageCollected<XRViewport>(0, 0, framebuffer_width,
framebuffer_height);
}
}
HTMLCanvasElement* XRWebGLLayer::output_canvas() const {
if (!framebuffer_) {
return webgl_context_->canvas();
}
return nullptr;
}
WebGLTexture* XRWebGLLayer::GetCameraTexture() {
DVLOG(1) << __func__;
// We already have a WebGL texture for the camera image - return it:
if (camera_image_texture_) {
return camera_image_texture_.Get();
}
// We don't have a WebGL texture, and we cannot create it - return null:
if (!camera_image_shared_image_texture_) {
return nullptr;
}
// We don't have a WebGL texture, but we can create it, so create, store and
// return it:
camera_image_texture_ = MakeGarbageCollected<WebGLUnownedTexture>(
webgl_context_, camera_image_shared_image_texture_->id(), GL_TEXTURE_2D);
return camera_image_texture_.Get();
}
void XRWebGLLayer::OnFrameStart() {
if (framebuffer_) {
framebuffer_->MarkOpaqueBufferComplete(true);
framebuffer_->SetContentsChanged(false);
const XRLayerSharedImages& layer_shared_images = GetSharedImages();
const XRSharedImageData& content_image_data =
layer_shared_images.content_image_data;
const XRSharedImageData& camera_image_data =
layer_shared_images.camera_image_data;
if (content_image_data.shared_image) {
drawing_buffer_->UseSharedBuffer(content_image_data.shared_image,
content_image_data.sync_token);
DVLOG(3) << __func__ << ": content_image_data.shared_image->mailbox()="
<< content_image_data.shared_image->mailbox().ToDebugString();
is_direct_draw_frame = true;
} else {
is_direct_draw_frame = false;
}
if (camera_image_data.shared_image) {
DVLOG(3) << __func__ << ": camera_image_data.shared_image->mailbox()"
<< camera_image_data.shared_image->mailbox().ToDebugString();
CreateAndBindCameraBufferTexture(camera_image_data.shared_image,
camera_image_data.sync_token);
}
}
}
void XRWebGLLayer::CreateAndBindCameraBufferTexture(
const scoped_refptr<gpu::ClientSharedImage>& buffer_shared_image,
const gpu::SyncToken& buffer_sync_token) {
gpu::gles2::GLES2Interface* gl = drawing_buffer_->ContextGL();
DVLOG(3) << __func__
<< ": buffer_sync_token=" << buffer_sync_token.ToDebugString();
camera_image_shared_image_texture_ = buffer_shared_image->CreateGLTexture(gl);
DVLOG(3) << __func__ << ": camera_image_shared_image_texture_->id()="
<< camera_image_shared_image_texture_->id();
if (buffer_shared_image) {
uint32_t texture_target = buffer_shared_image->GetTextureTarget();
camera_image_texture_scoped_access_ =
camera_image_shared_image_texture_->BeginAccess(buffer_sync_token,
/*readonly=*/true);
gl->BindTexture(texture_target,
camera_image_texture_scoped_access_->texture_id());
}
}
void XRWebGLLayer::OnFrameEnd() {
// The session might have ended in the middle of the frame. Only perform the
// main work of OnFrameEnd if it's still valid. Otherwise, simply ensure the
// shared image access is properly ended.
if (session()->ended()) {
if (is_direct_draw_frame) {
drawing_buffer_->DoneWithSharedBuffer();
is_direct_draw_frame = false;
}
if (camera_image_texture_scoped_access_) {
gpu::SharedImageTexture::ScopedAccess::EndAccess(
std::move(camera_image_texture_scoped_access_));
camera_image_shared_image_texture_.reset();
}
return;
}
if (framebuffer_) {
framebuffer_->MarkOpaqueBufferComplete(false);
if (is_direct_draw_frame) {
drawing_buffer_->DoneWithSharedBuffer();
is_direct_draw_frame = false;
}
// Submit the frame to the XR compositor.
if (session()->immersive()) {
bool framebuffer_dirty = framebuffer_->HaveContentsChanged();
// Not drawing to the framebuffer during a session's rAF callback is
// usually a sign that something is wrong, such as the app drawing to the
// wrong render target. Show a warning in the console if we see that
// happen too many times.
if (!framebuffer_dirty) {
// If the session doesn't have a pose then the framebuffer being clean
// may be expected, so we won't count those frames.
bool frame_had_pose = !!session()->GetMojoFrom(
device::mojom::blink::XRReferenceSpaceType::kViewer);
if (frame_had_pose) {
clean_frame_count++;
if (clean_frame_count == kCleanFrameWarningLimit) {
session()->xr()->GetExecutionContext()->AddConsoleMessage(
MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering,
mojom::blink::ConsoleMessageLevel::kWarning,
kCleanFrameWarning));
}
}
}
// Need to stop accessing the camera image texture before calling
// `SubmitWebGLLayer` so that we stop using it before the sync token
// that `SubmitWebGLLayer` will generate.
if (camera_image_shared_image_texture_) {
const XRLayerSharedImages& layer_shared_images = GetSharedImages();
// We shouldn't ever have a camera texture if the holder wasn't present:
CHECK(layer_shared_images.camera_image_data.shared_image);
DVLOG(3) << __func__
<< ": deleting camera image texture, "
"camera_image_shared_image_texture_->id()="
<< camera_image_shared_image_texture_->id();
gpu::SharedImageTexture::ScopedAccess::EndAccess(
std::move(camera_image_texture_scoped_access_));
camera_image_shared_image_texture_.reset();
// Notify our WebGLUnownedTexture (created from
// camera_image_shared_image_texture_) that we have deleted it. Also,
// release the reference since we no longer need it (note that it could
// still be kept alive by the JS application, but should be a defunct
// object).
if (camera_image_texture_) {
camera_image_texture_->OnGLDeleteTextures();
camera_image_texture_ = nullptr;
}
}
// Always call submit, but notify if the contents were changed or not.
session()->xr()->frameProvider()->SubmitWebGLLayer(this,
framebuffer_dirty);
}
}
}
void XRWebGLLayer::OnResize() {
if (drawing_buffer_) {
gfx::SizeF framebuffers_size = session()->RecommendedFramebufferSize();
gfx::Size desired_size = gfx::ToFlooredSize(
gfx::ScaleSize(framebuffers_size, framebuffer_scale_));
drawing_buffer_->Resize(desired_size);
}
// With both immersive and non-immersive session the viewports should be
// recomputed when the output canvas resizes.
viewports_dirty_ = true;
}
scoped_refptr<StaticBitmapImage> XRWebGLLayer::TransferToStaticBitmapImage() {
if (drawing_buffer_) {
return drawing_buffer_->TransferToStaticBitmapImage();
}
return nullptr;
}
void XRWebGLLayer::Trace(Visitor* visitor) const {
visitor->Trace(left_viewport_);
visitor->Trace(right_viewport_);
visitor->Trace(webgl_context_);
visitor->Trace(framebuffer_);
visitor->Trace(camera_image_texture_);
XRLayer::Trace(visitor);
}
} // namespace blink
|