Hash :
87187835
Author :
Date :
2022-04-07T13:51:10
Metal: For readPixels copy IOSurface to non-IOSurface texture For intel GPU/Drivers, it's faster to copy an IOSurface texture to a non-IOSurface texture and read from the copy than it is to read directly from the IOSurface texture. Bug: angleproject:7117 Change-Id: I786009444480f75be6feb05f09f87fb45a3186b1 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/3573078 Reviewed-by: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kyle Piddington <kpiddington@apple.com> Commit-Queue: Gregg Tavares <gman@chromium.org>
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 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
//
// 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_resources.mm:
// Implements wrapper classes for Metal's MTLTexture and MTLBuffer.
//
#include "libANGLE/renderer/metal/mtl_resources.h"
#include <TargetConditionals.h>
#include <algorithm>
#include "common/debug.h"
#include "libANGLE/renderer/metal/ContextMtl.h"
#include "libANGLE/renderer/metal/DisplayMtl.h"
#include "libANGLE/renderer/metal/mtl_command_buffer.h"
#include "libANGLE/renderer/metal/mtl_context_device.h"
#include "libANGLE/renderer/metal/mtl_format_utils.h"
#include "libANGLE/renderer/metal/mtl_utils.h"
namespace rx
{
namespace mtl
{
namespace
{
inline NSUInteger GetMipSize(NSUInteger baseSize, const MipmapNativeLevel level)
{
return std::max<NSUInteger>(1, baseSize >> level.get());
}
// Asynchronously synchronize the content of a resource between GPU memory and its CPU cache.
// NOTE: This operation doesn't finish immediately upon function's return.
template <class T>
void InvokeCPUMemSync(ContextMtl *context, mtl::BlitCommandEncoder *blitEncoder, T *resource)
{
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
if (blitEncoder)
{
blitEncoder->synchronizeResource(resource);
resource->resetCPUReadMemNeedSync();
resource->setCPUReadMemSyncPending(true);
}
#endif
}
template <class T>
void EnsureCPUMemWillBeSynced(ContextMtl *context, T *resource)
{
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
// Make sure GPU & CPU contents are synchronized.
// NOTE: Only MacOS has separated storage for resource on CPU and GPU and needs explicit
// synchronization
if (resource->get().storageMode == MTLStorageModeManaged && resource->isCPUReadMemNeedSync())
{
mtl::BlitCommandEncoder *blitEncoder = context->getBlitCommandEncoder();
InvokeCPUMemSync(context, blitEncoder, resource);
}
#endif
resource->resetCPUReadMemNeedSync();
}
} // namespace
// Resource implementation
Resource::Resource() : mUsageRef(std::make_shared<UsageRef>()) {}
// Share the GPU usage ref with other resource
Resource::Resource(Resource *other) : mUsageRef(other->mUsageRef)
{
ASSERT(mUsageRef);
}
void Resource::reset()
{
mUsageRef->cmdBufferQueueSerial = 0;
resetCPUReadMemDirty();
resetCPUReadMemNeedSync();
resetCPUReadMemSyncPending();
}
bool Resource::isBeingUsedByGPU(Context *context) const
{
return context->cmdQueue().isResourceBeingUsedByGPU(this);
}
bool Resource::hasPendingWorks(Context *context) const
{
return context->cmdQueue().resourceHasPendingWorks(this);
}
void Resource::setUsedByCommandBufferWithQueueSerial(uint64_t serial, bool writing)
{
if (writing)
{
mUsageRef->cpuReadMemNeedSync = true;
mUsageRef->cpuReadMemDirty = true;
}
mUsageRef->cmdBufferQueueSerial = std::max(mUsageRef->cmdBufferQueueSerial, serial);
}
// Texture implemenetation
/** static */
angle::Result Texture::Make2DTexture(ContextMtl *context,
const Format &format,
uint32_t width,
uint32_t height,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format.metalFormat
width:width
height:height
mipmapped:mips == 0 || mips > 1];
return MakeTexture(context, format, desc, mips, renderTargetOnly, allowFormatView, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::MakeMemoryLess2DTexture(ContextMtl *context,
const Format &format,
uint32_t width,
uint32_t height,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format.metalFormat
width:width
height:height
mipmapped:NO];
return MakeTexture(context, format, desc, 1, true, false, true, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::MakeCubeTexture(ContextMtl *context,
const Format &format,
uint32_t size,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
MTLTextureDescriptor *desc =
[MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:format.metalFormat
size:size
mipmapped:mips == 0 || mips > 1];
return MakeTexture(context, format, desc, mips, renderTargetOnly, allowFormatView, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::Make2DMSTexture(ContextMtl *context,
const Format &format,
uint32_t width,
uint32_t height,
uint32_t samples,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
MTLTextureDescriptor *desc = [[MTLTextureDescriptor new] ANGLE_MTL_AUTORELEASE];
desc.textureType = MTLTextureType2DMultisample;
desc.pixelFormat = format.metalFormat;
desc.width = width;
desc.height = height;
desc.mipmapLevelCount = 1;
desc.sampleCount = samples;
return MakeTexture(context, format, desc, 1, renderTargetOnly, allowFormatView, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::Make2DArrayTexture(ContextMtl *context,
const Format &format,
uint32_t width,
uint32_t height,
uint32_t mips,
uint32_t arrayLength,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
// Use texture2DDescriptorWithPixelFormat to calculate full range mipmap range:
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format.metalFormat
width:width
height:height
mipmapped:mips == 0 || mips > 1];
desc.textureType = MTLTextureType2DArray;
desc.arrayLength = arrayLength;
return MakeTexture(context, format, desc, mips, renderTargetOnly, allowFormatView, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::Make3DTexture(ContextMtl *context,
const Format &format,
uint32_t width,
uint32_t height,
uint32_t depth,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
ANGLE_MTL_OBJC_SCOPE
{
// Use texture2DDescriptorWithPixelFormat to calculate full range mipmap range:
uint32_t maxDimen = std::max(width, height);
maxDimen = std::max(maxDimen, depth);
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format.metalFormat
width:maxDimen
height:maxDimen
mipmapped:mips == 0 || mips > 1];
desc.textureType = MTLTextureType3D;
desc.width = width;
desc.height = height;
desc.depth = depth;
return MakeTexture(context, format, desc, mips, renderTargetOnly, allowFormatView, refOut);
} // ANGLE_MTL_OBJC_SCOPE
}
/** static */
angle::Result Texture::MakeTexture(ContextMtl *context,
const Format &mtlFormat,
MTLTextureDescriptor *desc,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
TextureRef *refOut)
{
return MakeTexture(context, mtlFormat, desc, mips, renderTargetOnly, allowFormatView, false,
refOut);
}
angle::Result Texture::MakeTexture(ContextMtl *context,
const Format &mtlFormat,
MTLTextureDescriptor *desc,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
bool memoryLess,
TextureRef *refOut)
{
if (desc.pixelFormat == MTLPixelFormatInvalid)
{
return angle::Result::Stop;
}
refOut->reset(new Texture(context, desc, mips, renderTargetOnly, allowFormatView, memoryLess));
if (!refOut || !refOut->get())
{
ANGLE_MTL_CHECK(context, false, GL_OUT_OF_MEMORY);
}
if (!mtlFormat.hasDepthAndStencilBits())
{
refOut->get()->setColorWritableMask(GetEmulatedColorWriteMask(mtlFormat));
}
size_t estimatedBytes = EstimateTextureSizeInBytes(
mtlFormat, desc.width, desc.height, desc.depth, desc.sampleCount, desc.mipmapLevelCount);
if (refOut)
{
refOut->get()->setEstimatedByteSize(memoryLess ? 0 : estimatedBytes);
}
return angle::Result::Continue;
}
angle::Result Texture::MakeTexture(ContextMtl *context,
const Format &mtlFormat,
MTLTextureDescriptor *desc,
IOSurfaceRef surfaceRef,
NSUInteger slice,
bool renderTargetOnly,
TextureRef *refOut)
{
refOut->reset(new Texture(context, desc, surfaceRef, slice, renderTargetOnly));
if (!(*refOut) || !(*refOut)->get())
{
ANGLE_MTL_CHECK(context, false, GL_OUT_OF_MEMORY);
}
if (!mtlFormat.hasDepthAndStencilBits())
{
refOut->get()->setColorWritableMask(GetEmulatedColorWriteMask(mtlFormat));
}
size_t estimatedBytes = EstimateTextureSizeInBytes(
mtlFormat, desc.width, desc.height, desc.depth, desc.sampleCount, desc.mipmapLevelCount);
refOut->get()->setEstimatedByteSize(estimatedBytes);
return angle::Result::Continue;
}
bool needMultisampleColorFormatShaderReadWorkaround(ContextMtl *context, MTLTextureDescriptor *desc)
{
return desc.sampleCount > 1 &&
context->getDisplay()
->getFeatures()
.multisampleColorFormatShaderReadWorkaround.enabled &&
context->getNativeFormatCaps(desc.pixelFormat).colorRenderable;
}
/** static */
TextureRef Texture::MakeFromMetal(id<MTLTexture> metalTexture)
{
ANGLE_MTL_OBJC_SCOPE { return TextureRef(new Texture(metalTexture)); }
}
Texture::Texture(id<MTLTexture> metalTexture)
: mColorWritableMask(std::make_shared<MTLColorWriteMask>(MTLColorWriteMaskAll))
{
set(metalTexture);
}
Texture::Texture(ContextMtl *context,
MTLTextureDescriptor *desc,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView)
: Texture(context, desc, mips, renderTargetOnly, allowFormatView, false)
{}
Texture::Texture(ContextMtl *context,
MTLTextureDescriptor *desc,
uint32_t mips,
bool renderTargetOnly,
bool allowFormatView,
bool memoryLess)
: mColorWritableMask(std::make_shared<MTLColorWriteMask>(MTLColorWriteMaskAll))
{
ANGLE_MTL_OBJC_SCOPE
{
const mtl::ContextDevice &metalDevice = context->getMetalDevice();
if (mips > 1 && mips < desc.mipmapLevelCount)
{
desc.mipmapLevelCount = mips;
}
// Every texture will support being rendered for now
desc.usage = 0;
if (context->getNativeFormatCaps(desc.pixelFormat).isRenderable())
{
desc.usage |= MTLTextureUsageRenderTarget;
}
if (memoryLess)
{
#if (TARGET_OS_IOS || TARGET_OS_TV) && !TARGET_OS_MACCATALYST
desc.resourceOptions = MTLResourceStorageModeMemoryless;
#else
desc.resourceOptions = MTLResourceStorageModePrivate;
#endif
}
else if (context->getNativeFormatCaps(desc.pixelFormat).depthRenderable ||
desc.textureType == MTLTextureType2DMultisample)
{
// Metal doesn't support host access to depth stencil texture's data
desc.resourceOptions = MTLResourceStorageModePrivate;
}
if (!renderTargetOnly || needMultisampleColorFormatShaderReadWorkaround(context, desc))
{
desc.usage = desc.usage | MTLTextureUsageShaderRead;
if (context->getNativeFormatCaps(desc.pixelFormat).writable)
{
desc.usage = desc.usage | MTLTextureUsageShaderWrite;
}
}
if (desc.pixelFormat == MTLPixelFormatDepth32Float_Stencil8)
{
ASSERT(allowFormatView);
}
if (allowFormatView)
{
desc.usage = desc.usage | MTLTextureUsagePixelFormatView;
}
set(metalDevice.newTextureWithDescriptor(desc));
mCreationDesc.retainAssign(desc);
}
}
Texture::Texture(ContextMtl *context,
MTLTextureDescriptor *desc,
IOSurfaceRef iosurface,
NSUInteger plane,
bool renderTargetOnly)
: mColorWritableMask(std::make_shared<MTLColorWriteMask>(MTLColorWriteMaskAll))
{
ANGLE_MTL_OBJC_SCOPE
{
const mtl::ContextDevice &metalDevice = context->getMetalDevice();
// Every texture will support being rendered for now
desc.usage = MTLTextureUsagePixelFormatView;
if (context->getNativeFormatCaps(desc.pixelFormat).isRenderable())
{
desc.usage |= MTLTextureUsageRenderTarget;
}
#if (TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH) && !TARGET_OS_MACCATALYST
desc.resourceOptions = MTLResourceStorageModeShared;
#else
desc.resourceOptions = MTLResourceStorageModeManaged;
#endif
if (!renderTargetOnly)
{
desc.usage = desc.usage | MTLTextureUsageShaderRead;
if (context->getNativeFormatCaps(desc.pixelFormat).writable)
{
desc.usage = desc.usage | MTLTextureUsageShaderWrite;
}
}
set(metalDevice.newTextureWithDescriptor(desc, iosurface, plane));
}
}
Texture::Texture(Texture *original, MTLPixelFormat format)
: Resource(original),
mColorWritableMask(original->mColorWritableMask) // Share color write mask property
{
ANGLE_MTL_OBJC_SCOPE
{
auto view = [original->get() newTextureViewWithPixelFormat:format];
set([view ANGLE_MTL_AUTORELEASE]);
// Texture views consume no additional memory
mEstimatedByteSize = 0;
}
}
Texture::Texture(Texture *original, MTLTextureType type, NSRange mipmapLevelRange, NSRange slices)
: Resource(original),
mColorWritableMask(original->mColorWritableMask) // Share color write mask property
{
ANGLE_MTL_OBJC_SCOPE
{
auto view = [original->get() newTextureViewWithPixelFormat:original->pixelFormat()
textureType:type
levels:mipmapLevelRange
slices:slices];
set([view ANGLE_MTL_AUTORELEASE]);
// Texture views consume no additional memory
mEstimatedByteSize = 0;
}
}
Texture::Texture(Texture *original, const TextureSwizzleChannels &swizzle)
: Resource(original),
mColorWritableMask(original->mColorWritableMask) // Share color write mask property
{
#if ANGLE_MTL_SWIZZLE_AVAILABLE
ANGLE_MTL_OBJC_SCOPE
{
auto view = [original->get()
newTextureViewWithPixelFormat:original->pixelFormat()
textureType:original->textureType()
levels:NSMakeRange(0, original->mipmapLevels())
slices:NSMakeRange(0, original->cubeFacesOrArrayLength())
swizzle:swizzle];
set([view ANGLE_MTL_AUTORELEASE]);
// Texture views consume no additional memory
mEstimatedByteSize = 0;
}
#else
UNREACHABLE();
#endif
}
void Texture::syncContent(ContextMtl *context, mtl::BlitCommandEncoder *blitEncoder)
{
InvokeCPUMemSync(context, blitEncoder, this);
}
void Texture::syncContentIfNeeded(ContextMtl *context)
{
EnsureCPUMemWillBeSynced(context, this);
}
bool Texture::isCPUAccessible() const
{
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
if (get().storageMode == MTLStorageModeManaged)
{
return true;
}
#endif
return get().storageMode == MTLStorageModeShared;
}
bool Texture::isShaderReadable() const
{
return get().usage & MTLTextureUsageShaderRead;
}
bool Texture::supportFormatView() const
{
return get().usage & MTLTextureUsagePixelFormatView;
}
void Texture::replace2DRegion(ContextMtl *context,
const MTLRegion ®ion,
const MipmapNativeLevel &mipmapLevel,
uint32_t slice,
const uint8_t *data,
size_t bytesPerRow)
{
ASSERT(region.size.depth == 1);
replaceRegion(context, region, mipmapLevel, slice, data, bytesPerRow, 0);
}
void Texture::replaceRegion(ContextMtl *context,
const MTLRegion ®ion,
const MipmapNativeLevel &mipmapLevel,
uint32_t slice,
const uint8_t *data,
size_t bytesPerRow,
size_t bytesPer2DImage)
{
if (mipmapLevel.get() >= this->mipmapLevels())
{
return;
}
ASSERT(isCPUAccessible());
CommandQueue &cmdQueue = context->cmdQueue();
syncContentIfNeeded(context);
// NOTE(hqle): what if multiple contexts on multiple threads are using this texture?
if (this->isBeingUsedByGPU(context))
{
context->flushCommandBuffer(mtl::NoWait);
}
cmdQueue.ensureResourceReadyForCPU(this);
if (textureType() != MTLTextureType3D)
{
bytesPer2DImage = 0;
}
[get() replaceRegion:region
mipmapLevel:mipmapLevel.get()
slice:slice
withBytes:data
bytesPerRow:bytesPerRow
bytesPerImage:bytesPer2DImage];
}
void Texture::getBytes(ContextMtl *context,
size_t bytesPerRow,
size_t bytesPer2DInage,
const MTLRegion ®ion,
const MipmapNativeLevel &mipmapLevel,
uint32_t slice,
uint8_t *dataOut)
{
ASSERT(isCPUAccessible());
CommandQueue &cmdQueue = context->cmdQueue();
syncContentIfNeeded(context);
// NOTE(hqle): what if multiple contexts on multiple threads are using this texture?
if (this->isBeingUsedByGPU(context))
{
context->flushCommandBuffer(mtl::NoWait);
}
cmdQueue.ensureResourceReadyForCPU(this);
[get() getBytes:dataOut
bytesPerRow:bytesPerRow
bytesPerImage:bytesPer2DInage
fromRegion:region
mipmapLevel:mipmapLevel.get()
slice:slice];
}
TextureRef Texture::createCubeFaceView(uint32_t face)
{
ANGLE_MTL_OBJC_SCOPE
{
switch (textureType())
{
case MTLTextureTypeCube:
return TextureRef(new Texture(
this, MTLTextureType2D, NSMakeRange(0, mipmapLevels()), NSMakeRange(face, 1)));
default:
UNREACHABLE();
return nullptr;
}
}
}
TextureRef Texture::createSliceMipView(uint32_t slice, const MipmapNativeLevel &level)
{
ANGLE_MTL_OBJC_SCOPE
{
switch (textureType())
{
case MTLTextureTypeCube:
case MTLTextureType2D:
case MTLTextureType2DArray:
return TextureRef(new Texture(this, MTLTextureType2D, NSMakeRange(level.get(), 1),
NSMakeRange(slice, 1)));
default:
UNREACHABLE();
return nullptr;
}
}
}
TextureRef Texture::createMipView(const MipmapNativeLevel &level)
{
ANGLE_MTL_OBJC_SCOPE
{
NSUInteger slices = cubeFacesOrArrayLength();
return TextureRef(
new Texture(this, textureType(), NSMakeRange(level.get(), 1), NSMakeRange(0, slices)));
}
}
TextureRef Texture::createViewWithDifferentFormat(MTLPixelFormat format)
{
ASSERT(supportFormatView());
return TextureRef(new Texture(this, format));
}
TextureRef Texture::createViewWithCompatibleFormat(MTLPixelFormat format)
{
return TextureRef(new Texture(this, format));
}
TextureRef Texture::createSwizzleView(const TextureSwizzleChannels &swizzle)
{
#if ANGLE_MTL_SWIZZLE_AVAILABLE
return TextureRef(new Texture(this, swizzle));
#else
WARN() << "Texture swizzle is not supported on pre iOS 13.0 and macOS 15.0";
UNIMPLEMENTED();
return shared_from_this();
#endif
}
MTLPixelFormat Texture::pixelFormat() const
{
return get().pixelFormat;
}
MTLTextureType Texture::textureType() const
{
return get().textureType;
}
uint32_t Texture::mipmapLevels() const
{
return static_cast<uint32_t>(get().mipmapLevelCount);
}
uint32_t Texture::arrayLength() const
{
return static_cast<uint32_t>(get().arrayLength);
}
uint32_t Texture::cubeFacesOrArrayLength() const
{
if (textureType() == MTLTextureTypeCube)
{
return 6;
}
return arrayLength();
}
uint32_t Texture::width(const MipmapNativeLevel &level) const
{
return static_cast<uint32_t>(GetMipSize(get().width, level));
}
uint32_t Texture::height(const MipmapNativeLevel &level) const
{
return static_cast<uint32_t>(GetMipSize(get().height, level));
}
uint32_t Texture::depth(const MipmapNativeLevel &level) const
{
return static_cast<uint32_t>(GetMipSize(get().depth, level));
}
gl::Extents Texture::size(const MipmapNativeLevel &level) const
{
gl::Extents re;
re.width = width(level);
re.height = height(level);
re.depth = depth(level);
return re;
}
gl::Extents Texture::size(const ImageNativeIndex &index) const
{
gl::Extents extents = size(index.getNativeLevel());
if (index.hasLayer())
{
extents.depth = 1;
}
return extents;
}
uint32_t Texture::samples() const
{
return static_cast<uint32_t>(get().sampleCount);
}
bool Texture::hasIOSurface() const
{
return (get().iosurface) != nullptr;
}
bool Texture::sameTypeAndDimemsionsAs(const TextureRef &other) const
{
return textureType() == other->textureType() && pixelFormat() == other->pixelFormat() &&
mipmapLevels() == other->mipmapLevels() &&
cubeFacesOrArrayLength() == other->cubeFacesOrArrayLength() &&
widthAt0() == other->widthAt0() && heightAt0() == other->heightAt0() &&
depthAt0() == other->depthAt0();
}
angle::Result Texture::resize(ContextMtl *context, uint32_t width, uint32_t height)
{
// Resizing texture view is not supported.
ASSERT(mCreationDesc);
ANGLE_MTL_OBJC_SCOPE
{
MTLTextureDescriptor *newDesc = [[mCreationDesc.get() copy] ANGLE_MTL_AUTORELEASE];
newDesc.width = width;
newDesc.height = height;
auto newTexture = context->getMetalDevice().newTextureWithDescriptor(newDesc);
ANGLE_CHECK_GL_ALLOC(context, newTexture);
mCreationDesc.retainAssign(newDesc);
set(newTexture);
// Reset reference counter
Resource::reset();
}
return angle::Result::Continue;
}
TextureRef Texture::getLinearColorView()
{
if (mLinearColorView)
{
return mLinearColorView;
}
switch (pixelFormat())
{
case MTLPixelFormatRGBA8Unorm_sRGB:
mLinearColorView = createViewWithCompatibleFormat(MTLPixelFormatRGBA8Unorm);
break;
case MTLPixelFormatBGRA8Unorm_sRGB:
mLinearColorView = createViewWithCompatibleFormat(MTLPixelFormatBGRA8Unorm);
break;
default:
// NOTE(hqle): Not all sRGB formats are supported yet.
UNREACHABLE();
}
return mLinearColorView;
}
TextureRef Texture::getReadableCopy(ContextMtl *context,
mtl::BlitCommandEncoder *encoder,
const uint32_t levelToCopy,
const uint32_t sliceToCopy,
const MTLRegion &areaToCopy)
{
gl::Extents firstLevelSize = size(kZeroNativeMipLevel);
if (!mReadCopy || mReadCopy->get().width < static_cast<size_t>(firstLevelSize.width) ||
mReadCopy->get().height < static_cast<size_t>(firstLevelSize.height))
{
// Create a texture that big enough to store the first level data and any smaller level
ANGLE_MTL_OBJC_SCOPE
{
auto desc = [[MTLTextureDescriptor new] ANGLE_MTL_AUTORELEASE];
desc.textureType = get().textureType;
desc.pixelFormat = get().pixelFormat;
desc.width = firstLevelSize.width;
desc.height = firstLevelSize.height;
desc.depth = 1;
desc.arrayLength = 1;
desc.resourceOptions = MTLResourceStorageModePrivate;
desc.sampleCount = get().sampleCount;
desc.usage = MTLTextureUsageShaderRead | MTLTextureUsagePixelFormatView;
mReadCopy.reset(new Texture(context->getMetalDevice().newTextureWithDescriptor(desc)));
} // ANGLE_MTL_OBJC_SCOPE
}
ASSERT(encoder);
encoder->copyTexture(shared_from_this(), sliceToCopy, mtl::MipmapNativeLevel(levelToCopy),
mReadCopy, 0, mtl::kZeroNativeMipLevel, 1, 1);
return mReadCopy;
}
void Texture::releaseReadableCopy()
{
mReadCopy = nullptr;
}
TextureRef Texture::getStencilView()
{
if (mStencilView)
{
return mStencilView;
}
switch (pixelFormat())
{
case MTLPixelFormatStencil8:
case MTLPixelFormatX32_Stencil8:
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
case MTLPixelFormatX24_Stencil8:
#endif
return mStencilView = shared_from_this();
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
case MTLPixelFormatDepth24Unorm_Stencil8:
mStencilView = createViewWithDifferentFormat(MTLPixelFormatX24_Stencil8);
break;
#endif
case MTLPixelFormatDepth32Float_Stencil8:
mStencilView = createViewWithDifferentFormat(MTLPixelFormatX32_Stencil8);
break;
default:
UNREACHABLE();
}
return mStencilView;
}
void Texture::set(id<MTLTexture> metalTexture)
{
ParentClass::set(metalTexture);
// Reset stencil view
mStencilView = nullptr;
mLinearColorView = nullptr;
}
// Buffer implementation
angle::Result Buffer::MakeBuffer(ContextMtl *context,
size_t size,
const uint8_t *data,
BufferRef *bufferOut)
{
return MakeBufferWithSharedMemOpt(context, false, size, data, bufferOut);
}
angle::Result Buffer::MakeBufferWithSharedMemOpt(ContextMtl *context,
bool forceUseSharedMem,
size_t size,
const uint8_t *data,
BufferRef *bufferOut)
{
bufferOut->reset(new Buffer(context, forceUseSharedMem, size, data));
if (!(*bufferOut) || !(*bufferOut)->get())
{
ANGLE_MTL_CHECK(context, false, GL_OUT_OF_MEMORY);
}
return angle::Result::Continue;
}
angle::Result Buffer::MakeBufferWithResOpt(ContextMtl *context,
MTLResourceOptions options,
size_t size,
const uint8_t *data,
BufferRef *bufferOut)
{
bufferOut->reset(new Buffer(context, options, size, data));
if (!(*bufferOut) || !(*bufferOut)->get())
{
ANGLE_MTL_CHECK(context, false, GL_OUT_OF_MEMORY);
}
return angle::Result::Continue;
}
Buffer::Buffer(ContextMtl *context, bool forceUseSharedMem, size_t size, const uint8_t *data)
{
(void)resetWithSharedMemOpt(context, forceUseSharedMem, size, data);
}
Buffer::Buffer(ContextMtl *context, MTLResourceOptions options, size_t size, const uint8_t *data)
{
(void)resetWithResOpt(context, options, size, data);
}
angle::Result Buffer::reset(ContextMtl *context, size_t size, const uint8_t *data)
{
return resetWithSharedMemOpt(context, false, size, data);
}
angle::Result Buffer::resetWithSharedMemOpt(ContextMtl *context,
bool forceUseSharedMem,
size_t size,
const uint8_t *data)
{
MTLResourceOptions options;
options = 0;
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
if (!forceUseSharedMem || context->getDisplay()->getFeatures().forceBufferGPUStorage.enabled)
{
options |= MTLResourceStorageModeManaged;
}
else
#endif
{
options |= MTLResourceStorageModeShared;
}
return resetWithResOpt(context, options, size, data);
}
angle::Result Buffer::resetWithResOpt(ContextMtl *context,
MTLResourceOptions options,
size_t size,
const uint8_t *data)
{
set([&] {
const mtl::ContextDevice &metalDevice = context->getMetalDevice();
if (data)
{
return metalDevice.newBufferWithBytes(data, size, options);
}
return metalDevice.newBufferWithLength(size, options);
}());
// Reset command buffer's reference serial
Resource::reset();
return angle::Result::Continue;
}
void Buffer::syncContent(ContextMtl *context, mtl::BlitCommandEncoder *blitEncoder)
{
InvokeCPUMemSync(context, blitEncoder, this);
}
const uint8_t *Buffer::mapReadOnly(ContextMtl *context)
{
return mapWithOpt(context, true, false);
}
uint8_t *Buffer::map(ContextMtl *context)
{
return mapWithOpt(context, false, false);
}
uint8_t *Buffer::mapWithOpt(ContextMtl *context, bool readonly, bool noSync)
{
mMapReadOnly = readonly;
if (!noSync && (isCPUReadMemSyncPending() || isCPUReadMemNeedSync() || !readonly))
{
CommandQueue &cmdQueue = context->cmdQueue();
EnsureCPUMemWillBeSynced(context, this);
if (this->isBeingUsedByGPU(context))
{
context->flushCommandBuffer(mtl::NoWait);
}
cmdQueue.ensureResourceReadyForCPU(this);
resetCPUReadMemSyncPending();
}
return reinterpret_cast<uint8_t *>([get() contents]);
}
void Buffer::unmap(ContextMtl *context)
{
flush(context, 0, size());
// Reset read only flag
mMapReadOnly = true;
}
void Buffer::unmapNoFlush(ContextMtl *context)
{
mMapReadOnly = true;
}
void Buffer::unmapAndFlushSubset(ContextMtl *context, size_t offsetWritten, size_t sizeWritten)
{
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
flush(context, offsetWritten, sizeWritten);
#endif
mMapReadOnly = true;
}
void Buffer::flush(ContextMtl *context, size_t offsetWritten, size_t sizeWritten)
{
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
if (!mMapReadOnly)
{
if (get().storageMode == MTLStorageModeManaged)
{
size_t startOffset = std::min(offsetWritten, size());
size_t endOffset = std::min(offsetWritten + sizeWritten, size());
size_t clampedSize = endOffset - startOffset;
if (clampedSize > 0)
{
[get() didModifyRange:NSMakeRange(startOffset, clampedSize)];
}
}
}
#endif
}
size_t Buffer::size() const
{
return get().length;
}
bool Buffer::useSharedMem() const
{
return get().storageMode == MTLStorageModeShared;
}
}
}