Hash :
bb6e512e
Author :
Date :
2021-03-09T16:17:54
Mtl: Add Apple vendor ID On M1 Macs we need to extract Apple's vendor ID. Bug: chromium:1131248 Change-Id: Ie0e4006c3005e0a252d7a27a069a3be47ef4a7d5 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2745703 Reviewed-by: Yuly Novikov <ynovikov@chromium.org> Reviewed-by: Jamie Madill <jmadill@chromium.org> Commit-Queue: Jonah Ryan-Davis <jonahr@google.com>
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 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// mtl_utils.mm:
// Implements utilities functions that create Metal shaders, convert from angle enums
// to Metal enums and so on.
//
#include "libANGLE/renderer/metal/mtl_utils.h"
#include <TargetConditionals.h>
#include "common/MemoryBuffer.h"
#include "gpu_info_util/SystemInfo.h"
#include "libANGLE/renderer/metal/ContextMtl.h"
#include "libANGLE/renderer/metal/DisplayMtl.h"
#include "libANGLE/renderer/metal/RenderTargetMtl.h"
#include "libANGLE/renderer/metal/mtl_render_utils.h"
namespace rx
{
namespace mtl
{
namespace
{
uint32_t GetDeviceVendorIdFromName(id<MTLDevice> metalDevice)
{
struct Vendor
{
NSString *const trademark;
uint32_t vendorId;
};
constexpr Vendor kVendors[] = {
{@"AMD", angle::kVendorID_AMD}, {@"Apple", angle::kVendorID_Apple},
{@"Radeon", angle::kVendorID_AMD}, {@"Intel", angle::kVendorID_Intel},
{@"Geforce", angle::kVendorID_NVIDIA}, {@"Quadro", angle::kVendorID_NVIDIA}};
ANGLE_MTL_OBJC_SCOPE
{
if (metalDevice)
{
for (const Vendor &it : kVendors)
{
if ([metalDevice.name rangeOfString:it.trademark].location != NSNotFound)
{
return it.vendorId;
}
}
}
return 0;
}
}
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
uint32_t GetDeviceVendorIdFromIOKit(id<MTLDevice> device)
{
return angle::GetVendorIDFromMetalDeviceRegistryID(device.registryID);
}
#endif
void GetSliceAndDepth(const ImageNativeIndex &index, GLint *layer, GLint *startDepth)
{
*layer = *startDepth = 0;
if (!index.hasLayer())
{
return;
}
switch (index.getType())
{
case gl::TextureType::CubeMap:
*layer = index.cubeMapFaceIndex();
break;
case gl::TextureType::_2DArray:
*layer = index.getLayerIndex();
break;
case gl::TextureType::_3D:
*startDepth = index.getLayerIndex();
break;
default:
break;
}
}
GLint GetSliceOrDepth(const ImageNativeIndex &index)
{
GLint layer, startDepth;
GetSliceAndDepth(index, &layer, &startDepth);
return std::max(layer, startDepth);
}
}
angle::Result InitializeTextureContents(const gl::Context *context,
const TextureRef &texture,
const Format &textureObjFormat,
const ImageNativeIndex &index)
{
ASSERT(texture && texture->valid());
// Only one slice can be initialized at a time.
ASSERT(!index.isLayered() || index.getType() == gl::TextureType::_3D);
ContextMtl *contextMtl = mtl::GetImpl(context);
const gl::InternalFormat &intendedInternalFormat = textureObjFormat.intendedInternalFormat();
// This function is called in many places to initialize the content of a texture.
// So it's better we do the initial check here instead of let the callers do it themselves:
if (!textureObjFormat.valid() || intendedInternalFormat.compressed)
{
return angle::Result::Continue;
}
gl::Extents size = texture->size(index);
// Intiialize the content to black
GLint layer, startDepth;
GetSliceAndDepth(index, &layer, &startDepth);
if (texture->isCPUAccessible() && index.getType() != gl::TextureType::_2DMultisample &&
index.getType() != gl::TextureType::_2DMultisampleArray)
{
const angle::Format &dstFormat = angle::Format::Get(textureObjFormat.actualFormatId);
const size_t dstRowPitch = dstFormat.pixelBytes * size.width;
angle::MemoryBuffer conversionRow;
ANGLE_CHECK_GL_ALLOC(contextMtl, conversionRow.resize(dstRowPitch));
if (textureObjFormat.initFunction)
{
textureObjFormat.initFunction(size.width, 1, 1, conversionRow.data(), dstRowPitch, 0);
}
else
{
const angle::Format &srcFormat = angle::Format::Get(
intendedInternalFormat.alphaBits > 0 ? angle::FormatID::R8G8B8A8_UNORM
: angle::FormatID::R8G8B8_UNORM);
const size_t srcRowPitch = srcFormat.pixelBytes * size.width;
angle::MemoryBuffer srcRow;
ANGLE_CHECK_GL_ALLOC(contextMtl, srcRow.resize(srcRowPitch));
memset(srcRow.data(), 0, srcRowPitch);
CopyImageCHROMIUM(srcRow.data(), srcRowPitch, srcFormat.pixelBytes, 0,
srcFormat.pixelReadFunction, conversionRow.data(), dstRowPitch,
dstFormat.pixelBytes, 0, dstFormat.pixelWriteFunction,
intendedInternalFormat.format, dstFormat.componentType, size.width, 1,
1, false, false, false);
}
auto mtlRowRegion = MTLRegionMake2D(0, 0, size.width, 1);
for (NSUInteger d = 0; d < static_cast<NSUInteger>(size.depth); ++d)
{
mtlRowRegion.origin.z = d + startDepth;
for (NSUInteger r = 0; r < static_cast<NSUInteger>(size.height); ++r)
{
mtlRowRegion.origin.y = r;
// Upload to texture
texture->replace2DRegion(contextMtl, mtlRowRegion, index.getNativeLevel(), layer,
conversionRow.data(), dstRowPitch);
}
}
}
else
{
ANGLE_TRY(InitializeTextureContentsGPU(context, texture, textureObjFormat, index,
MTLColorWriteMaskAll));
}
return angle::Result::Continue;
}
angle::Result InitializeTextureContentsGPU(const gl::Context *context,
const TextureRef &texture,
const Format &textureObjFormat,
const ImageNativeIndex &index,
MTLColorWriteMask channelsToInit)
{
// Only one slice can be initialized at a time.
ASSERT(!index.isLayered() || index.getType() == gl::TextureType::_3D);
if (index.isLayered() && index.getType() == gl::TextureType::_3D)
{
ImageNativeIndexIterator ite =
index.getLayerIterator(texture->depth(index.getNativeLevel()));
while (ite.hasNext())
{
ImageNativeIndex depthLayerIndex = ite.next();
ANGLE_TRY(InitializeTextureContentsGPU(context, texture, textureObjFormat,
depthLayerIndex, MTLColorWriteMaskAll));
}
return angle::Result::Continue;
}
if (textureObjFormat.hasDepthOrStencilBits())
{
// Depth stencil texture needs dedicated function.
return InitializeDepthStencilTextureContentsGPU(context, texture, textureObjFormat, index);
}
ContextMtl *contextMtl = mtl::GetImpl(context);
GLint sliceOrDepth = GetSliceOrDepth(index);
// Use clear render command
RenderTargetMtl tempRtt;
tempRtt.set(texture, index.getNativeLevel(), sliceOrDepth, textureObjFormat);
int clearAlpha = 0;
if (!textureObjFormat.intendedAngleFormat().alphaBits)
{
// if intended format doesn't have alpha, set it to 1.0.
clearAlpha = kEmulatedAlphaValue;
}
RenderCommandEncoder *encoder;
if (channelsToInit == MTLColorWriteMaskAll)
{
// If all channels will be initialized, use clear loadOp.
Optional<MTLClearColor> blackColor = MTLClearColorMake(0, 0, 0, clearAlpha);
encoder = contextMtl->getRenderTargetCommandEncoderWithClear(tempRtt, blackColor);
}
else
{
// temporarily enable color channels requested via channelsToInit. Some emulated format has
// some channels write mask disabled when the texture is created.
MTLColorWriteMask oldMask = texture->getColorWritableMask();
texture->setColorWritableMask(channelsToInit);
// If there are some channels don't need to be initialized, we must use clearWithDraw.
encoder = contextMtl->getRenderTargetCommandEncoder(tempRtt);
const angle::Format &angleFormat = textureObjFormat.actualAngleFormat();
ClearRectParams clearParams;
ClearColorValue clearColor;
if (angleFormat.isSint())
{
clearColor.setAsInt(0, 0, 0, clearAlpha);
}
else if (angleFormat.isUint())
{
clearColor.setAsUInt(0, 0, 0, clearAlpha);
}
else
{
clearColor.setAsFloat(0, 0, 0, clearAlpha);
}
clearParams.clearColor = clearColor;
clearParams.dstTextureSize = texture->sizeAt0();
clearParams.enabledBuffers.set(0);
clearParams.clearArea = gl::Rectangle(0, 0, texture->widthAt0(), texture->heightAt0());
ANGLE_TRY(
contextMtl->getDisplay()->getUtils().clearWithDraw(context, encoder, clearParams));
// Restore texture's intended write mask
texture->setColorWritableMask(oldMask);
}
encoder->setStoreAction(MTLStoreActionStore);
return angle::Result::Continue;
}
angle::Result InitializeDepthStencilTextureContentsGPU(const gl::Context *context,
const TextureRef &texture,
const Format &textureObjFormat,
const ImageNativeIndex &index)
{
const MipmapNativeLevel &level = index.getNativeLevel();
// Use clear operation
ContextMtl *contextMtl = mtl::GetImpl(context);
const angle::Format &angleFormat = textureObjFormat.actualAngleFormat();
mtl::RenderPassDesc rpDesc;
uint32_t layer = index.hasLayer() ? index.getLayerIndex() : 0;
rpDesc.sampleCount = texture->samples();
if (angleFormat.depthBits)
{
rpDesc.depthAttachment.texture = texture;
rpDesc.depthAttachment.level = level;
rpDesc.depthAttachment.sliceOrDepth = layer;
rpDesc.depthAttachment.loadAction = MTLLoadActionClear;
rpDesc.depthAttachment.clearDepth = 1.0;
}
if (angleFormat.stencilBits)
{
rpDesc.stencilAttachment.texture = texture;
rpDesc.stencilAttachment.level = level;
rpDesc.stencilAttachment.sliceOrDepth = layer;
rpDesc.stencilAttachment.loadAction = MTLLoadActionClear;
}
// End current render pass
contextMtl->endEncoding(true);
RenderCommandEncoder *encoder = contextMtl->getRenderPassCommandEncoder(rpDesc);
encoder->setStoreAction(MTLStoreActionStore);
return angle::Result::Continue;
}
angle::Result ReadTexturePerSliceBytes(const gl::Context *context,
const TextureRef &texture,
size_t bytesPerRow,
const gl::Rectangle &fromRegion,
const MipmapNativeLevel &mipLevel,
uint32_t sliceOrDepth,
uint8_t *dataOut)
{
ASSERT(texture && texture->valid());
ContextMtl *contextMtl = mtl::GetImpl(context);
GLint layer = 0;
GLint startDepth = 0;
switch (texture->textureType())
{
case MTLTextureTypeCube:
case MTLTextureType2DArray:
layer = sliceOrDepth;
break;
case MTLTextureType3D:
startDepth = sliceOrDepth;
break;
default:
break;
}
MTLRegion mtlRegion = MTLRegionMake3D(fromRegion.x, fromRegion.y, startDepth, fromRegion.width,
fromRegion.height, 1);
texture->getBytes(contextMtl, bytesPerRow, 0, mtlRegion, mipLevel, layer, dataOut);
return angle::Result::Continue;
}
angle::Result ReadTexturePerSliceBytesToBuffer(const gl::Context *context,
const TextureRef &texture,
size_t bytesPerRow,
const gl::Rectangle &fromRegion,
const MipmapNativeLevel &mipLevel,
uint32_t sliceOrDepth,
uint32_t dstOffset,
const BufferRef &dstBuffer)
{
ASSERT(texture && texture->valid());
ContextMtl *contextMtl = mtl::GetImpl(context);
GLint layer = 0;
GLint startDepth = 0;
switch (texture->textureType())
{
case MTLTextureTypeCube:
case MTLTextureType2DArray:
layer = sliceOrDepth;
break;
case MTLTextureType3D:
startDepth = sliceOrDepth;
break;
default:
break;
}
MTLRegion mtlRegion = MTLRegionMake3D(fromRegion.x, fromRegion.y, startDepth, fromRegion.width,
fromRegion.height, 1);
BlitCommandEncoder *blitEncoder = contextMtl->getBlitCommandEncoder();
blitEncoder->copyTextureToBuffer(texture, layer, mipLevel, mtlRegion.origin, mtlRegion.size,
dstBuffer, dstOffset, bytesPerRow, 0, MTLBlitOptionNone);
return angle::Result::Continue;
}
MTLViewport GetViewport(const gl::Rectangle &rect, double znear, double zfar)
{
MTLViewport re;
re.originX = rect.x;
re.originY = rect.y;
re.width = rect.width;
re.height = rect.height;
re.znear = znear;
re.zfar = zfar;
return re;
}
MTLViewport GetViewportFlipY(const gl::Rectangle &rect,
NSUInteger screenHeight,
double znear,
double zfar)
{
MTLViewport re;
re.originX = rect.x;
re.originY = static_cast<double>(screenHeight) - rect.y1();
re.width = rect.width;
re.height = rect.height;
re.znear = znear;
re.zfar = zfar;
return re;
}
MTLViewport GetViewport(const gl::Rectangle &rect,
NSUInteger screenHeight,
bool flipY,
double znear,
double zfar)
{
if (flipY)
{
return GetViewportFlipY(rect, screenHeight, znear, zfar);
}
return GetViewport(rect, znear, zfar);
}
MTLScissorRect GetScissorRect(const gl::Rectangle &rect, NSUInteger screenHeight, bool flipY)
{
MTLScissorRect re;
re.x = rect.x;
re.y = flipY ? (screenHeight - rect.y1()) : rect.y;
re.width = rect.width;
re.height = rect.height;
return re;
}
uint32_t GetDeviceVendorId(id<MTLDevice> metalDevice)
{
uint32_t vendorId = 0;
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
if (ANGLE_APPLE_AVAILABLE_XC(10.13, 13.0))
{
vendorId = GetDeviceVendorIdFromIOKit(metalDevice);
}
#endif
if (!vendorId)
{
vendorId = GetDeviceVendorIdFromName(metalDevice);
}
return vendorId;
}
AutoObjCPtr<id<MTLLibrary>> CreateShaderLibrary(id<MTLDevice> metalDevice,
const std::string &source,
AutoObjCPtr<NSError *> *error)
{
return CreateShaderLibrary(metalDevice, source.c_str(), source.size(), error);
}
AutoObjCPtr<id<MTLLibrary>> CreateShaderLibrary(id<MTLDevice> metalDevice,
const char *source,
size_t sourceLen,
AutoObjCPtr<NSError *> *errorOut)
{
ANGLE_MTL_OBJC_SCOPE
{
NSError *nsError = nil;
auto nsSource = [[NSString alloc] initWithBytesNoCopy:const_cast<char *>(source)
length:sourceLen
encoding:NSUTF8StringEncoding
freeWhenDone:NO];
auto options = [[[MTLCompileOptions alloc] init] ANGLE_MTL_AUTORELEASE];
auto library = [metalDevice newLibraryWithSource:nsSource options:options error:&nsError];
[nsSource ANGLE_MTL_AUTORELEASE];
*errorOut = std::move(nsError);
return [library ANGLE_MTL_AUTORELEASE];
}
}
AutoObjCPtr<id<MTLLibrary>> CreateShaderLibraryFromBinary(id<MTLDevice> metalDevice,
const uint8_t *binarySource,
size_t binarySourceLen,
AutoObjCPtr<NSError *> *errorOut)
{
ANGLE_MTL_OBJC_SCOPE
{
NSError *nsError = nil;
auto shaderSourceData =
dispatch_data_create(binarySource, binarySourceLen, dispatch_get_main_queue(),
^{
});
auto library = [metalDevice newLibraryWithData:shaderSourceData error:&nsError];
[shaderSourceData ANGLE_MTL_AUTORELEASE];
*errorOut = std::move(nsError);
return [library ANGLE_MTL_AUTORELEASE];
}
}
MTLTextureType GetTextureType(gl::TextureType glType)
{
switch (glType)
{
case gl::TextureType::_2D:
return MTLTextureType2D;
case gl::TextureType::CubeMap:
return MTLTextureTypeCube;
default:
return MTLTextureTypeInvalid;
}
}
MTLSamplerMinMagFilter GetFilter(GLenum filter)
{
switch (filter)
{
case GL_LINEAR_MIPMAP_LINEAR:
case GL_LINEAR_MIPMAP_NEAREST:
case GL_LINEAR:
return MTLSamplerMinMagFilterLinear;
case GL_NEAREST_MIPMAP_LINEAR:
case GL_NEAREST_MIPMAP_NEAREST:
case GL_NEAREST:
return MTLSamplerMinMagFilterNearest;
default:
UNIMPLEMENTED();
return MTLSamplerMinMagFilterNearest;
}
}
MTLSamplerMipFilter GetMipmapFilter(GLenum filter)
{
switch (filter)
{
case GL_LINEAR:
case GL_NEAREST:
return MTLSamplerMipFilterNotMipmapped;
case GL_LINEAR_MIPMAP_LINEAR:
case GL_NEAREST_MIPMAP_LINEAR:
return MTLSamplerMipFilterLinear;
case GL_NEAREST_MIPMAP_NEAREST:
case GL_LINEAR_MIPMAP_NEAREST:
return MTLSamplerMipFilterNearest;
default:
UNIMPLEMENTED();
return MTLSamplerMipFilterNotMipmapped;
}
}
MTLSamplerAddressMode GetSamplerAddressMode(GLenum wrap)
{
switch (wrap)
{
case GL_REPEAT:
return MTLSamplerAddressModeRepeat;
case GL_MIRRORED_REPEAT:
return MTLSamplerAddressModeMirrorRepeat;
case GL_CLAMP_TO_BORDER:
// ES doesn't have border support
return MTLSamplerAddressModeClampToEdge;
case GL_CLAMP_TO_EDGE:
return MTLSamplerAddressModeClampToEdge;
default:
UNIMPLEMENTED();
return MTLSamplerAddressModeClampToEdge;
}
}
MTLBlendFactor GetBlendFactor(GLenum factor)
{
switch (factor)
{
case GL_ZERO:
return MTLBlendFactorZero;
case GL_ONE:
return MTLBlendFactorOne;
case GL_SRC_COLOR:
return MTLBlendFactorSourceColor;
case GL_DST_COLOR:
return MTLBlendFactorDestinationColor;
case GL_ONE_MINUS_SRC_COLOR:
return MTLBlendFactorOneMinusSourceColor;
case GL_SRC_ALPHA:
return MTLBlendFactorSourceAlpha;
case GL_ONE_MINUS_SRC_ALPHA:
return MTLBlendFactorOneMinusSourceAlpha;
case GL_DST_ALPHA:
return MTLBlendFactorDestinationAlpha;
case GL_ONE_MINUS_DST_ALPHA:
return MTLBlendFactorOneMinusDestinationAlpha;
case GL_ONE_MINUS_DST_COLOR:
return MTLBlendFactorOneMinusDestinationColor;
case GL_SRC_ALPHA_SATURATE:
return MTLBlendFactorSourceAlphaSaturated;
case GL_CONSTANT_COLOR:
return MTLBlendFactorBlendColor;
case GL_CONSTANT_ALPHA:
return MTLBlendFactorBlendAlpha;
case GL_ONE_MINUS_CONSTANT_COLOR:
return MTLBlendFactorOneMinusBlendColor;
case GL_ONE_MINUS_CONSTANT_ALPHA:
return MTLBlendFactorOneMinusBlendAlpha;
default:
UNREACHABLE();
return MTLBlendFactorZero;
}
}
MTLBlendOperation GetBlendOp(GLenum op)
{
switch (op)
{
case GL_FUNC_ADD:
return MTLBlendOperationAdd;
case GL_FUNC_SUBTRACT:
return MTLBlendOperationSubtract;
case GL_FUNC_REVERSE_SUBTRACT:
return MTLBlendOperationReverseSubtract;
case GL_MIN:
return MTLBlendOperationMin;
case GL_MAX:
return MTLBlendOperationMax;
default:
UNREACHABLE();
return MTLBlendOperationAdd;
}
}
MTLCompareFunction GetCompareFunc(GLenum func)
{
switch (func)
{
case GL_NEVER:
return MTLCompareFunctionNever;
case GL_ALWAYS:
return MTLCompareFunctionAlways;
case GL_LESS:
return MTLCompareFunctionLess;
case GL_LEQUAL:
return MTLCompareFunctionLessEqual;
case GL_EQUAL:
return MTLCompareFunctionEqual;
case GL_GREATER:
return MTLCompareFunctionGreater;
case GL_GEQUAL:
return MTLCompareFunctionGreaterEqual;
case GL_NOTEQUAL:
return MTLCompareFunctionNotEqual;
default:
UNREACHABLE();
return MTLCompareFunctionAlways;
}
}
MTLStencilOperation GetStencilOp(GLenum op)
{
switch (op)
{
case GL_KEEP:
return MTLStencilOperationKeep;
case GL_ZERO:
return MTLStencilOperationZero;
case GL_REPLACE:
return MTLStencilOperationReplace;
case GL_INCR:
return MTLStencilOperationIncrementClamp;
case GL_DECR:
return MTLStencilOperationDecrementClamp;
case GL_INCR_WRAP:
return MTLStencilOperationIncrementWrap;
case GL_DECR_WRAP:
return MTLStencilOperationDecrementWrap;
case GL_INVERT:
return MTLStencilOperationInvert;
default:
UNREACHABLE();
return MTLStencilOperationKeep;
}
}
MTLWinding GetFontfaceWinding(GLenum frontFaceMode, bool invert)
{
switch (frontFaceMode)
{
case GL_CW:
return invert ? MTLWindingCounterClockwise : MTLWindingClockwise;
case GL_CCW:
return invert ? MTLWindingClockwise : MTLWindingCounterClockwise;
default:
UNREACHABLE();
return MTLWindingClockwise;
}
}
#if ANGLE_MTL_PRIMITIVE_TOPOLOGY_CLASS_AVAILABLE
PrimitiveTopologyClass GetPrimitiveTopologyClass(gl::PrimitiveMode mode)
{
// NOTE(hqle): Support layered renderring in future.
// In non-layered rendering mode, unspecified is enough.
return MTLPrimitiveTopologyClassUnspecified;
}
#else // ANGLE_MTL_PRIMITIVE_TOPOLOGY_CLASS_AVAILABLE
PrimitiveTopologyClass GetPrimitiveTopologyClass(gl::PrimitiveMode mode)
{
return kPrimitiveTopologyClassTriangle;
}
#endif
MTLPrimitiveType GetPrimitiveType(gl::PrimitiveMode mode)
{
switch (mode)
{
case gl::PrimitiveMode::Triangles:
return MTLPrimitiveTypeTriangle;
case gl::PrimitiveMode::Points:
return MTLPrimitiveTypePoint;
case gl::PrimitiveMode::Lines:
return MTLPrimitiveTypeLine;
case gl::PrimitiveMode::LineStrip:
case gl::PrimitiveMode::LineLoop:
return MTLPrimitiveTypeLineStrip;
case gl::PrimitiveMode::TriangleStrip:
return MTLPrimitiveTypeTriangleStrip;
case gl::PrimitiveMode::TriangleFan:
// NOTE(hqle): Emulate triangle fan.
default:
return MTLPrimitiveTypeInvalid;
}
}
MTLIndexType GetIndexType(gl::DrawElementsType type)
{
switch (type)
{
case gl::DrawElementsType::UnsignedShort:
return MTLIndexTypeUInt16;
case gl::DrawElementsType::UnsignedInt:
return MTLIndexTypeUInt32;
case gl::DrawElementsType::UnsignedByte:
// NOTE(hqle): Convert to supported type
default:
return MTLIndexTypeInvalid;
}
}
#if ANGLE_MTL_SWIZZLE_AVAILABLE
MTLTextureSwizzle GetTextureSwizzle(GLenum swizzle)
{
switch (swizzle)
{
case GL_RED:
return MTLTextureSwizzleRed;
case GL_GREEN:
return MTLTextureSwizzleGreen;
case GL_BLUE:
return MTLTextureSwizzleBlue;
case GL_ALPHA:
return MTLTextureSwizzleAlpha;
case GL_ZERO:
return MTLTextureSwizzleZero;
case GL_ONE:
return MTLTextureSwizzleOne;
default:
UNREACHABLE();
return MTLTextureSwizzleZero;
}
}
#endif
MTLColorWriteMask GetEmulatedColorWriteMask(const mtl::Format &mtlFormat, bool *isEmulatedOut)
{
const angle::Format &intendedFormat = mtlFormat.intendedAngleFormat();
const angle::Format &actualFormat = mtlFormat.actualAngleFormat();
bool isFormatEmulated = false;
MTLColorWriteMask colorWritableMask = MTLColorWriteMaskAll;
if (intendedFormat.alphaBits == 0 && actualFormat.alphaBits)
{
isFormatEmulated = true;
// Disable alpha write to this texture
colorWritableMask = colorWritableMask & (~MTLColorWriteMaskAlpha);
}
if (intendedFormat.luminanceBits == 0)
{
if (intendedFormat.redBits == 0 && actualFormat.redBits)
{
isFormatEmulated = true;
// Disable red write to this texture
colorWritableMask = colorWritableMask & (~MTLColorWriteMaskRed);
}
if (intendedFormat.greenBits == 0 && actualFormat.greenBits)
{
isFormatEmulated = true;
// Disable green write to this texture
colorWritableMask = colorWritableMask & (~MTLColorWriteMaskGreen);
}
if (intendedFormat.blueBits == 0 && actualFormat.blueBits)
{
isFormatEmulated = true;
// Disable blue write to this texture
colorWritableMask = colorWritableMask & (~MTLColorWriteMaskBlue);
}
}
*isEmulatedOut = isFormatEmulated;
return colorWritableMask;
}
MTLColorWriteMask GetEmulatedColorWriteMask(const mtl::Format &mtlFormat)
{
// Ignore isFormatEmulated boolean value
bool isFormatEmulated;
return GetEmulatedColorWriteMask(mtlFormat, &isFormatEmulated);
}
bool IsFormatEmulated(const mtl::Format &mtlFormat)
{
bool isFormatEmulated;
(void)GetEmulatedColorWriteMask(mtlFormat, &isFormatEmulated);
return isFormatEmulated;
}
MTLClearColor EmulatedAlphaClearColor(MTLClearColor color, MTLColorWriteMask colorMask)
{
MTLClearColor re = color;
if (!(colorMask & MTLColorWriteMaskAlpha))
{
re.alpha = kEmulatedAlphaValue;
}
return re;
}
gl::Box MTLRegionToGLBox(const MTLRegion &mtlRegion)
{
return gl::Box(static_cast<int>(mtlRegion.origin.x), static_cast<int>(mtlRegion.origin.y),
static_cast<int>(mtlRegion.origin.z), static_cast<int>(mtlRegion.size.width),
static_cast<int>(mtlRegion.size.height), static_cast<int>(mtlRegion.size.depth));
}
MipmapNativeLevel GetNativeMipLevel(GLuint level, GLuint base)
{
ASSERT(level >= base);
return MipmapNativeLevel(level - base);
}
GLuint GetGLMipLevel(const MipmapNativeLevel &nativeLevel, GLuint base)
{
return nativeLevel.get() + base;
}
angle::Result TriangleFanBoundCheck(ContextMtl *context, size_t numTris)
{
bool indexCheck =
(numTris > std::numeric_limits<unsigned int>::max() / (sizeof(unsigned int) * 3));
ANGLE_CHECK(context, !indexCheck,
"Failed to create a scratch index buffer for GL_TRIANGLE_FAN, "
"too many indices required.",
GL_OUT_OF_MEMORY);
return angle::Result::Continue;
}
angle::Result GetTriangleFanIndicesCount(ContextMtl *context,
GLsizei vetexCount,
uint32_t *numElemsOut)
{
size_t numTris = vetexCount - 2;
ANGLE_TRY(TriangleFanBoundCheck(context, numTris));
size_t numIndices = numTris * 3;
ANGLE_CHECK(context, numIndices <= std::numeric_limits<uint32_t>::max(),
"Failed to create a scratch index buffer for GL_TRIANGLE_FAN, "
"too many indices required.",
GL_OUT_OF_MEMORY);
*numElemsOut = static_cast<uint32_t>(numIndices);
return angle::Result::Continue;
}
} // namespace mtl
} // namespace rx