hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ec9e45004bff3391d902ca13f1b2a732803d13e7 | 35,185 | c | C | drivers/gpu/drm/amd/amdgpu/amdgpu_object.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/gpu/drm/amd/amdgpu/amdgpu_object.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/gpu/drm/amd/amdgpu/amdgpu_object.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | /*
* Copyright 2009 Jerome Glisse.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
*/
/*
* Authors:
* Jerome Glisse <glisse@freedesktop.org>
* Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
* Dave Airlie
*/
#include <linux/list.h>
#include <linux/slab.h>
#include <drm/drmP.h>
#include <drm/amdgpu_drm.h>
#include <drm/drm_cache.h>
#include "amdgpu.h"
#include "amdgpu_trace.h"
#include "amdgpu_amdkfd.h"
/**
* DOC: amdgpu_object
*
* This defines the interfaces to operate on an &amdgpu_bo buffer object which
* represents memory used by driver (VRAM, system memory, etc.). The driver
* provides DRM/GEM APIs to userspace. DRM/GEM APIs then use these interfaces
* to create/destroy/set buffer object which are then managed by the kernel TTM
* memory manager.
* The interfaces are also used internally by kernel clients, including gfx,
* uvd, etc. for kernel managed allocations used by the GPU.
*
*/
/**
* amdgpu_bo_subtract_pin_size - Remove BO from pin_size accounting
*
* @bo: &amdgpu_bo buffer object
*
* This function is called when a BO stops being pinned, and updates the
* &amdgpu_device pin_size values accordingly.
*/
static void amdgpu_bo_subtract_pin_size(struct amdgpu_bo *bo)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
if (bo->tbo.mem.mem_type == TTM_PL_VRAM) {
atomic64_sub(amdgpu_bo_size(bo), &adev->vram_pin_size);
atomic64_sub(amdgpu_vram_mgr_bo_visible_size(bo),
&adev->visible_pin_size);
} else if (bo->tbo.mem.mem_type == TTM_PL_TT) {
atomic64_sub(amdgpu_bo_size(bo), &adev->gart_pin_size);
}
}
static void amdgpu_bo_destroy(struct ttm_buffer_object *tbo)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
struct amdgpu_bo *bo = ttm_to_amdgpu_bo(tbo);
if (bo->pin_count > 0)
amdgpu_bo_subtract_pin_size(bo);
if (bo->kfd_bo)
amdgpu_amdkfd_unreserve_memory_limit(bo);
amdgpu_bo_kunmap(bo);
if (bo->gem_base.import_attach)
drm_prime_gem_destroy(&bo->gem_base, bo->tbo.sg);
drm_gem_object_release(&bo->gem_base);
amdgpu_bo_unref(&bo->parent);
if (!list_empty(&bo->shadow_list)) {
mutex_lock(&adev->shadow_list_lock);
list_del_init(&bo->shadow_list);
mutex_unlock(&adev->shadow_list_lock);
}
kfree(bo->metadata);
kfree(bo);
}
/**
* amdgpu_bo_is_amdgpu_bo - check if the buffer object is an &amdgpu_bo
* @bo: buffer object to be checked
*
* Uses destroy function associated with the object to determine if this is
* an &amdgpu_bo.
*
* Returns:
* true if the object belongs to &amdgpu_bo, false if not.
*/
bool amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object *bo)
{
if (bo->destroy == &amdgpu_bo_destroy)
return true;
return false;
}
/**
* amdgpu_bo_placement_from_domain - set buffer's placement
* @abo: &amdgpu_bo buffer object whose placement is to be set
* @domain: requested domain
*
* Sets buffer's placement according to requested domain and the buffer's
* flags.
*/
void amdgpu_bo_placement_from_domain(struct amdgpu_bo *abo, u32 domain)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
struct ttm_placement *placement = &abo->placement;
struct ttm_place *places = abo->placements;
u64 flags = abo->flags;
u32 c = 0;
if (domain & AMDGPU_GEM_DOMAIN_VRAM) {
unsigned visible_pfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_WC | TTM_PL_FLAG_UNCACHED |
TTM_PL_FLAG_VRAM;
if (flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)
places[c].lpfn = visible_pfn;
else
places[c].flags |= TTM_PL_FLAG_TOPDOWN;
if (flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)
places[c].flags |= TTM_PL_FLAG_CONTIGUOUS;
c++;
}
if (domain & AMDGPU_GEM_DOMAIN_GTT) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_TT;
if (flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
places[c].flags |= TTM_PL_FLAG_WC |
TTM_PL_FLAG_UNCACHED;
else
places[c].flags |= TTM_PL_FLAG_CACHED;
c++;
}
if (domain & AMDGPU_GEM_DOMAIN_CPU) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_SYSTEM;
if (flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
places[c].flags |= TTM_PL_FLAG_WC |
TTM_PL_FLAG_UNCACHED;
else
places[c].flags |= TTM_PL_FLAG_CACHED;
c++;
}
if (domain & AMDGPU_GEM_DOMAIN_GDS) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_UNCACHED | AMDGPU_PL_FLAG_GDS;
c++;
}
if (domain & AMDGPU_GEM_DOMAIN_GWS) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_UNCACHED | AMDGPU_PL_FLAG_GWS;
c++;
}
if (domain & AMDGPU_GEM_DOMAIN_OA) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_FLAG_UNCACHED | AMDGPU_PL_FLAG_OA;
c++;
}
if (!c) {
places[c].fpfn = 0;
places[c].lpfn = 0;
places[c].flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_SYSTEM;
c++;
}
BUG_ON(c >= AMDGPU_BO_MAX_PLACEMENTS);
placement->num_placement = c;
placement->placement = places;
placement->num_busy_placement = c;
placement->busy_placement = places;
}
/**
* amdgpu_bo_create_reserved - create reserved BO for kernel use
*
* @adev: amdgpu device object
* @size: size for the new BO
* @align: alignment for the new BO
* @domain: where to place it
* @bo_ptr: used to initialize BOs in structures
* @gpu_addr: GPU addr of the pinned BO
* @cpu_addr: optional CPU address mapping
*
* Allocates and pins a BO for kernel internal use, and returns it still
* reserved.
*
* Note: For bo_ptr new BO is only created if bo_ptr points to NULL.
*
* Returns:
* 0 on success, negative error code otherwise.
*/
int amdgpu_bo_create_reserved(struct amdgpu_device *adev,
unsigned long size, int align,
u32 domain, struct amdgpu_bo **bo_ptr,
u64 *gpu_addr, void **cpu_addr)
{
struct amdgpu_bo_param bp;
bool free = false;
int r;
if (!size) {
amdgpu_bo_unref(bo_ptr);
return 0;
}
memset(&bp, 0, sizeof(bp));
bp.size = size;
bp.byte_align = align;
bp.domain = domain;
bp.flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
bp.type = ttm_bo_type_kernel;
bp.resv = NULL;
if (!*bo_ptr) {
r = amdgpu_bo_create(adev, &bp, bo_ptr);
if (r) {
dev_err(adev->dev, "(%d) failed to allocate kernel bo\n",
r);
return r;
}
free = true;
}
r = amdgpu_bo_reserve(*bo_ptr, false);
if (r) {
dev_err(adev->dev, "(%d) failed to reserve kernel bo\n", r);
goto error_free;
}
r = amdgpu_bo_pin(*bo_ptr, domain);
if (r) {
dev_err(adev->dev, "(%d) kernel bo pin failed\n", r);
goto error_unreserve;
}
r = amdgpu_ttm_alloc_gart(&(*bo_ptr)->tbo);
if (r) {
dev_err(adev->dev, "%p bind failed\n", *bo_ptr);
goto error_unpin;
}
if (gpu_addr)
*gpu_addr = amdgpu_bo_gpu_offset(*bo_ptr);
if (cpu_addr) {
r = amdgpu_bo_kmap(*bo_ptr, cpu_addr);
if (r) {
dev_err(adev->dev, "(%d) kernel bo map failed\n", r);
goto error_unpin;
}
}
return 0;
error_unpin:
amdgpu_bo_unpin(*bo_ptr);
error_unreserve:
amdgpu_bo_unreserve(*bo_ptr);
error_free:
if (free)
amdgpu_bo_unref(bo_ptr);
return r;
}
/**
* amdgpu_bo_create_kernel - create BO for kernel use
*
* @adev: amdgpu device object
* @size: size for the new BO
* @align: alignment for the new BO
* @domain: where to place it
* @bo_ptr: used to initialize BOs in structures
* @gpu_addr: GPU addr of the pinned BO
* @cpu_addr: optional CPU address mapping
*
* Allocates and pins a BO for kernel internal use.
*
* Note: For bo_ptr new BO is only created if bo_ptr points to NULL.
*
* Returns:
* 0 on success, negative error code otherwise.
*/
int amdgpu_bo_create_kernel(struct amdgpu_device *adev,
unsigned long size, int align,
u32 domain, struct amdgpu_bo **bo_ptr,
u64 *gpu_addr, void **cpu_addr)
{
int r;
r = amdgpu_bo_create_reserved(adev, size, align, domain, bo_ptr,
gpu_addr, cpu_addr);
if (r)
return r;
if (*bo_ptr)
amdgpu_bo_unreserve(*bo_ptr);
return 0;
}
/**
* amdgpu_bo_free_kernel - free BO for kernel use
*
* @bo: amdgpu BO to free
* @gpu_addr: pointer to where the BO's GPU memory space address was stored
* @cpu_addr: pointer to where the BO's CPU memory space address was stored
*
* unmaps and unpin a BO for kernel internal use.
*/
void amdgpu_bo_free_kernel(struct amdgpu_bo **bo, u64 *gpu_addr,
void **cpu_addr)
{
if (*bo == NULL)
return;
if (likely(amdgpu_bo_reserve(*bo, true) == 0)) {
if (cpu_addr)
amdgpu_bo_kunmap(*bo);
amdgpu_bo_unpin(*bo);
amdgpu_bo_unreserve(*bo);
}
amdgpu_bo_unref(bo);
if (gpu_addr)
*gpu_addr = 0;
if (cpu_addr)
*cpu_addr = NULL;
}
/* Validate bo size is bit bigger then the request domain */
static bool amdgpu_bo_validate_size(struct amdgpu_device *adev,
unsigned long size, u32 domain)
{
struct ttm_mem_type_manager *man = NULL;
/*
* If GTT is part of requested domains the check must succeed to
* allow fall back to GTT
*/
if (domain & AMDGPU_GEM_DOMAIN_GTT) {
man = &adev->mman.bdev.man[TTM_PL_TT];
if (size < (man->size << PAGE_SHIFT))
return true;
else
goto fail;
}
if (domain & AMDGPU_GEM_DOMAIN_VRAM) {
man = &adev->mman.bdev.man[TTM_PL_VRAM];
if (size < (man->size << PAGE_SHIFT))
return true;
else
goto fail;
}
/* TODO add more domains checks, such as AMDGPU_GEM_DOMAIN_CPU */
return true;
fail:
DRM_DEBUG("BO size %lu > total memory in domain: %llu\n", size,
man->size << PAGE_SHIFT);
return false;
}
static int amdgpu_bo_do_create(struct amdgpu_device *adev,
struct amdgpu_bo_param *bp,
struct amdgpu_bo **bo_ptr)
{
struct ttm_operation_ctx ctx = {
.interruptible = (bp->type != ttm_bo_type_kernel),
.no_wait_gpu = false,
.resv = bp->resv,
.flags = TTM_OPT_FLAG_ALLOW_RES_EVICT
};
struct amdgpu_bo *bo;
unsigned long page_align, size = bp->size;
size_t acc_size;
int r;
/* Note that GDS/GWS/OA allocates 1 page per byte/resource. */
if (bp->domain & (AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA)) {
/* GWS and OA don't need any alignment. */
page_align = bp->byte_align;
size <<= PAGE_SHIFT;
} else if (bp->domain & AMDGPU_GEM_DOMAIN_GDS) {
/* Both size and alignment must be a multiple of 4. */
page_align = ALIGN(bp->byte_align, 4);
size = ALIGN(size, 4) << PAGE_SHIFT;
} else {
/* Memory should be aligned at least to a page size. */
page_align = ALIGN(bp->byte_align, PAGE_SIZE) >> PAGE_SHIFT;
size = ALIGN(size, PAGE_SIZE);
}
if (!amdgpu_bo_validate_size(adev, size, bp->domain))
return -ENOMEM;
*bo_ptr = NULL;
acc_size = ttm_bo_dma_acc_size(&adev->mman.bdev, size,
sizeof(struct amdgpu_bo));
bo = kzalloc(sizeof(struct amdgpu_bo), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
drm_gem_private_object_init(adev->ddev, &bo->gem_base, size);
INIT_LIST_HEAD(&bo->shadow_list);
bo->vm_bo = NULL;
bo->preferred_domains = bp->preferred_domain ? bp->preferred_domain :
bp->domain;
bo->allowed_domains = bo->preferred_domains;
if (bp->type != ttm_bo_type_kernel &&
bo->allowed_domains == AMDGPU_GEM_DOMAIN_VRAM)
bo->allowed_domains |= AMDGPU_GEM_DOMAIN_GTT;
bo->flags = bp->flags;
#ifdef CONFIG_X86_32
/* XXX: Write-combined CPU mappings of GTT seem broken on 32-bit
* See https://bugs.freedesktop.org/show_bug.cgi?id=84627
*/
bo->flags &= ~AMDGPU_GEM_CREATE_CPU_GTT_USWC;
#elif defined(CONFIG_X86) && !defined(CONFIG_X86_PAT)
/* Don't try to enable write-combining when it can't work, or things
* may be slow
* See https://bugs.freedesktop.org/show_bug.cgi?id=88758
*/
#ifndef CONFIG_COMPILE_TEST
#warning Please enable CONFIG_MTRR and CONFIG_X86_PAT for better performance \
thanks to write-combining
#endif
if (bo->flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
DRM_INFO_ONCE("Please enable CONFIG_MTRR and CONFIG_X86_PAT for "
"better performance thanks to write-combining\n");
bo->flags &= ~AMDGPU_GEM_CREATE_CPU_GTT_USWC;
#else
/* For architectures that don't support WC memory,
* mask out the WC flag from the BO
*/
if (!drm_arch_can_wc_memory())
bo->flags &= ~AMDGPU_GEM_CREATE_CPU_GTT_USWC;
#endif
bo->tbo.bdev = &adev->mman.bdev;
amdgpu_bo_placement_from_domain(bo, bp->domain);
if (bp->type == ttm_bo_type_kernel)
bo->tbo.priority = 1;
r = ttm_bo_init_reserved(&adev->mman.bdev, &bo->tbo, size, bp->type,
&bo->placement, page_align, &ctx, acc_size,
NULL, bp->resv, &amdgpu_bo_destroy);
if (unlikely(r != 0))
return r;
if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
bo->tbo.mem.mem_type == TTM_PL_VRAM &&
bo->tbo.mem.start < adev->gmc.visible_vram_size >> PAGE_SHIFT)
amdgpu_cs_report_moved_bytes(adev, ctx.bytes_moved,
ctx.bytes_moved);
else
amdgpu_cs_report_moved_bytes(adev, ctx.bytes_moved, 0);
if (bp->flags & AMDGPU_GEM_CREATE_VRAM_CLEARED &&
bo->tbo.mem.placement & TTM_PL_FLAG_VRAM) {
struct dma_fence *fence;
r = amdgpu_fill_buffer(bo, 0, bo->tbo.resv, &fence);
if (unlikely(r))
goto fail_unreserve;
amdgpu_bo_fence(bo, fence, false);
dma_fence_put(bo->tbo.moving);
bo->tbo.moving = dma_fence_get(fence);
dma_fence_put(fence);
}
if (!bp->resv)
amdgpu_bo_unreserve(bo);
*bo_ptr = bo;
trace_amdgpu_bo_create(bo);
/* Treat CPU_ACCESS_REQUIRED only as a hint if given by UMD */
if (bp->type == ttm_bo_type_device)
bo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
return 0;
fail_unreserve:
if (!bp->resv)
ww_mutex_unlock(&bo->tbo.resv->lock);
amdgpu_bo_unref(&bo);
return r;
}
static int amdgpu_bo_create_shadow(struct amdgpu_device *adev,
unsigned long size,
struct amdgpu_bo *bo)
{
struct amdgpu_bo_param bp;
int r;
if (bo->shadow)
return 0;
memset(&bp, 0, sizeof(bp));
bp.size = size;
bp.domain = AMDGPU_GEM_DOMAIN_GTT;
bp.flags = AMDGPU_GEM_CREATE_CPU_GTT_USWC |
AMDGPU_GEM_CREATE_SHADOW;
bp.type = ttm_bo_type_kernel;
bp.resv = bo->tbo.resv;
r = amdgpu_bo_do_create(adev, &bp, &bo->shadow);
if (!r) {
bo->shadow->parent = amdgpu_bo_ref(bo);
mutex_lock(&adev->shadow_list_lock);
list_add_tail(&bo->shadow->shadow_list, &adev->shadow_list);
mutex_unlock(&adev->shadow_list_lock);
}
return r;
}
/**
* amdgpu_bo_create - create an &amdgpu_bo buffer object
* @adev: amdgpu device object
* @bp: parameters to be used for the buffer object
* @bo_ptr: pointer to the buffer object pointer
*
* Creates an &amdgpu_bo buffer object; and if requested, also creates a
* shadow object.
* Shadow object is used to backup the original buffer object, and is always
* in GTT.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_create(struct amdgpu_device *adev,
struct amdgpu_bo_param *bp,
struct amdgpu_bo **bo_ptr)
{
u64 flags = bp->flags;
int r;
bp->flags = bp->flags & ~AMDGPU_GEM_CREATE_SHADOW;
r = amdgpu_bo_do_create(adev, bp, bo_ptr);
if (r)
return r;
if ((flags & AMDGPU_GEM_CREATE_SHADOW) && !(adev->flags & AMD_IS_APU)) {
if (!bp->resv)
WARN_ON(reservation_object_lock((*bo_ptr)->tbo.resv,
NULL));
r = amdgpu_bo_create_shadow(adev, bp->size, *bo_ptr);
if (!bp->resv)
reservation_object_unlock((*bo_ptr)->tbo.resv);
if (r)
amdgpu_bo_unref(bo_ptr);
}
return r;
}
/**
* amdgpu_bo_validate - validate an &amdgpu_bo buffer object
* @bo: pointer to the buffer object
*
* Sets placement according to domain; and changes placement and caching
* policy of the buffer object according to the placement.
* This is used for validating shadow bos. It calls ttm_bo_validate() to
* make sure the buffer is resident where it needs to be.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_validate(struct amdgpu_bo *bo)
{
struct ttm_operation_ctx ctx = { false, false };
uint32_t domain;
int r;
if (bo->pin_count)
return 0;
domain = bo->preferred_domains;
retry:
amdgpu_bo_placement_from_domain(bo, domain);
r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
if (unlikely(r == -ENOMEM) && domain != bo->allowed_domains) {
domain = bo->allowed_domains;
goto retry;
}
return r;
}
/**
* amdgpu_bo_restore_shadow - restore an &amdgpu_bo shadow
*
* @shadow: &amdgpu_bo shadow to be restored
* @fence: dma_fence associated with the operation
*
* Copies a buffer object's shadow content back to the object.
* This is used for recovering a buffer from its shadow in case of a gpu
* reset where vram context may be lost.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_restore_shadow(struct amdgpu_bo *shadow, struct dma_fence **fence)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(shadow->tbo.bdev);
struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
uint64_t shadow_addr, parent_addr;
shadow_addr = amdgpu_bo_gpu_offset(shadow);
parent_addr = amdgpu_bo_gpu_offset(shadow->parent);
return amdgpu_copy_buffer(ring, shadow_addr, parent_addr,
amdgpu_bo_size(shadow), NULL, fence,
true, false);
}
/**
* amdgpu_bo_kmap - map an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object to be mapped
* @ptr: kernel virtual address to be returned
*
* Calls ttm_bo_kmap() to set up the kernel virtual mapping; calls
* amdgpu_bo_kptr() to get the kernel virtual address.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_kmap(struct amdgpu_bo *bo, void **ptr)
{
void *kptr;
long r;
if (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)
return -EPERM;
kptr = amdgpu_bo_kptr(bo);
if (kptr) {
if (ptr)
*ptr = kptr;
return 0;
}
r = reservation_object_wait_timeout_rcu(bo->tbo.resv, false, false,
MAX_SCHEDULE_TIMEOUT);
if (r < 0)
return r;
r = ttm_bo_kmap(&bo->tbo, 0, bo->tbo.num_pages, &bo->kmap);
if (r)
return r;
if (ptr)
*ptr = amdgpu_bo_kptr(bo);
return 0;
}
/**
* amdgpu_bo_kptr - returns a kernel virtual address of the buffer object
* @bo: &amdgpu_bo buffer object
*
* Calls ttm_kmap_obj_virtual() to get the kernel virtual address
*
* Returns:
* the virtual address of a buffer object area.
*/
void *amdgpu_bo_kptr(struct amdgpu_bo *bo)
{
bool is_iomem;
return ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
}
/**
* amdgpu_bo_kunmap - unmap an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object to be unmapped
*
* Unmaps a kernel map set up by amdgpu_bo_kmap().
*/
void amdgpu_bo_kunmap(struct amdgpu_bo *bo)
{
if (bo->kmap.bo)
ttm_bo_kunmap(&bo->kmap);
}
/**
* amdgpu_bo_ref - reference an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object
*
* References the contained &ttm_buffer_object.
*
* Returns:
* a refcounted pointer to the &amdgpu_bo buffer object.
*/
struct amdgpu_bo *amdgpu_bo_ref(struct amdgpu_bo *bo)
{
if (bo == NULL)
return NULL;
ttm_bo_get(&bo->tbo);
return bo;
}
/**
* amdgpu_bo_unref - unreference an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object
*
* Unreferences the contained &ttm_buffer_object and clear the pointer
*/
void amdgpu_bo_unref(struct amdgpu_bo **bo)
{
struct ttm_buffer_object *tbo;
if ((*bo) == NULL)
return;
tbo = &((*bo)->tbo);
ttm_bo_put(tbo);
*bo = NULL;
}
/**
* amdgpu_bo_pin_restricted - pin an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object to be pinned
* @domain: domain to be pinned to
* @min_offset: the start of requested address range
* @max_offset: the end of requested address range
*
* Pins the buffer object according to requested domain and address range. If
* the memory is unbound gart memory, binds the pages into gart table. Adjusts
* pin_count and pin_size accordingly.
*
* Pinning means to lock pages in memory along with keeping them at a fixed
* offset. It is required when a buffer can not be moved, for example, when
* a display buffer is being scanned out.
*
* Compared with amdgpu_bo_pin(), this function gives more flexibility on
* where to pin a buffer if there are specific restrictions on where a buffer
* must be located.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_pin_restricted(struct amdgpu_bo *bo, u32 domain,
u64 min_offset, u64 max_offset)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
struct ttm_operation_ctx ctx = { false, false };
int r, i;
if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm))
return -EPERM;
if (WARN_ON_ONCE(min_offset > max_offset))
return -EINVAL;
/* A shared bo cannot be migrated to VRAM */
if (bo->prime_shared_count) {
if (domain & AMDGPU_GEM_DOMAIN_GTT)
domain = AMDGPU_GEM_DOMAIN_GTT;
else
return -EINVAL;
}
/* This assumes only APU display buffers are pinned with (VRAM|GTT).
* See function amdgpu_display_supported_domains()
*/
domain = amdgpu_bo_get_preferred_pin_domain(adev, domain);
if (bo->pin_count) {
uint32_t mem_type = bo->tbo.mem.mem_type;
if (!(domain & amdgpu_mem_type_to_domain(mem_type)))
return -EINVAL;
bo->pin_count++;
if (max_offset != 0) {
u64 domain_start = bo->tbo.bdev->man[mem_type].gpu_offset;
WARN_ON_ONCE(max_offset <
(amdgpu_bo_gpu_offset(bo) - domain_start));
}
return 0;
}
bo->flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
/* force to pin into visible video ram */
if (!(bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS))
bo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
amdgpu_bo_placement_from_domain(bo, domain);
for (i = 0; i < bo->placement.num_placement; i++) {
unsigned fpfn, lpfn;
fpfn = min_offset >> PAGE_SHIFT;
lpfn = max_offset >> PAGE_SHIFT;
if (fpfn > bo->placements[i].fpfn)
bo->placements[i].fpfn = fpfn;
if (!bo->placements[i].lpfn ||
(lpfn && lpfn < bo->placements[i].lpfn))
bo->placements[i].lpfn = lpfn;
bo->placements[i].flags |= TTM_PL_FLAG_NO_EVICT;
}
r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
if (unlikely(r)) {
dev_err(adev->dev, "%p pin failed\n", bo);
goto error;
}
bo->pin_count = 1;
domain = amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
if (domain == AMDGPU_GEM_DOMAIN_VRAM) {
atomic64_add(amdgpu_bo_size(bo), &adev->vram_pin_size);
atomic64_add(amdgpu_vram_mgr_bo_visible_size(bo),
&adev->visible_pin_size);
} else if (domain == AMDGPU_GEM_DOMAIN_GTT) {
atomic64_add(amdgpu_bo_size(bo), &adev->gart_pin_size);
}
error:
return r;
}
/**
* amdgpu_bo_pin - pin an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object to be pinned
* @domain: domain to be pinned to
*
* A simple wrapper to amdgpu_bo_pin_restricted().
* Provides a simpler API for buffers that do not have any strict restrictions
* on where a buffer must be located.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_pin(struct amdgpu_bo *bo, u32 domain)
{
return amdgpu_bo_pin_restricted(bo, domain, 0, 0);
}
/**
* amdgpu_bo_unpin - unpin an &amdgpu_bo buffer object
* @bo: &amdgpu_bo buffer object to be unpinned
*
* Decreases the pin_count, and clears the flags if pin_count reaches 0.
* Changes placement and pin size accordingly.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_unpin(struct amdgpu_bo *bo)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
struct ttm_operation_ctx ctx = { false, false };
int r, i;
if (WARN_ON_ONCE(!bo->pin_count)) {
dev_warn(adev->dev, "%p unpin not necessary\n", bo);
return 0;
}
bo->pin_count--;
if (bo->pin_count)
return 0;
amdgpu_bo_subtract_pin_size(bo);
for (i = 0; i < bo->placement.num_placement; i++) {
bo->placements[i].lpfn = 0;
bo->placements[i].flags &= ~TTM_PL_FLAG_NO_EVICT;
}
r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
if (unlikely(r))
dev_err(adev->dev, "%p validate failed for unpin\n", bo);
return r;
}
/**
* amdgpu_bo_evict_vram - evict VRAM buffers
* @adev: amdgpu device object
*
* Evicts all VRAM buffers on the lru list of the memory type.
* Mainly used for evicting vram at suspend time.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_evict_vram(struct amdgpu_device *adev)
{
/* late 2.6.33 fix IGP hibernate - we need pm ops to do this correct */
#ifndef CONFIG_HIBERNATION
if (adev->flags & AMD_IS_APU) {
/* Useless to evict on IGP chips */
return 0;
}
#endif
return ttm_bo_evict_mm(&adev->mman.bdev, TTM_PL_VRAM);
}
static const char *amdgpu_vram_names[] = {
"UNKNOWN",
"GDDR1",
"DDR2",
"GDDR3",
"GDDR4",
"GDDR5",
"HBM",
"DDR3",
"DDR4",
};
/**
* amdgpu_bo_init - initialize memory manager
* @adev: amdgpu device object
*
* Calls amdgpu_ttm_init() to initialize amdgpu memory manager.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_init(struct amdgpu_device *adev)
{
/* reserve PAT memory space to WC for VRAM */
arch_io_reserve_memtype_wc(adev->gmc.aper_base,
adev->gmc.aper_size);
/* Add an MTRR for the VRAM */
adev->gmc.vram_mtrr = arch_phys_wc_add(adev->gmc.aper_base,
adev->gmc.aper_size);
DRM_INFO("Detected VRAM RAM=%lluM, BAR=%lluM\n",
adev->gmc.mc_vram_size >> 20,
(unsigned long long)adev->gmc.aper_size >> 20);
DRM_INFO("RAM width %dbits %s\n",
adev->gmc.vram_width, amdgpu_vram_names[adev->gmc.vram_type]);
return amdgpu_ttm_init(adev);
}
/**
* amdgpu_bo_late_init - late init
* @adev: amdgpu device object
*
* Calls amdgpu_ttm_late_init() to free resources used earlier during
* initialization.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_late_init(struct amdgpu_device *adev)
{
amdgpu_ttm_late_init(adev);
return 0;
}
/**
* amdgpu_bo_fini - tear down memory manager
* @adev: amdgpu device object
*
* Reverses amdgpu_bo_init() to tear down memory manager.
*/
void amdgpu_bo_fini(struct amdgpu_device *adev)
{
amdgpu_ttm_fini(adev);
arch_phys_wc_del(adev->gmc.vram_mtrr);
arch_io_free_memtype_wc(adev->gmc.aper_base, adev->gmc.aper_size);
}
/**
* amdgpu_bo_fbdev_mmap - mmap fbdev memory
* @bo: &amdgpu_bo buffer object
* @vma: vma as input from the fbdev mmap method
*
* Calls ttm_fbdev_mmap() to mmap fbdev memory if it is backed by a bo.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_fbdev_mmap(struct amdgpu_bo *bo,
struct vm_area_struct *vma)
{
return ttm_fbdev_mmap(vma, &bo->tbo);
}
/**
* amdgpu_bo_set_tiling_flags - set tiling flags
* @bo: &amdgpu_bo buffer object
* @tiling_flags: new flags
*
* Sets buffer object's tiling flags with the new one. Used by GEM ioctl or
* kernel driver to set the tiling flags on a buffer.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_set_tiling_flags(struct amdgpu_bo *bo, u64 tiling_flags)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
if (adev->family <= AMDGPU_FAMILY_CZ &&
AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT) > 6)
return -EINVAL;
bo->tiling_flags = tiling_flags;
return 0;
}
/**
* amdgpu_bo_get_tiling_flags - get tiling flags
* @bo: &amdgpu_bo buffer object
* @tiling_flags: returned flags
*
* Gets buffer object's tiling flags. Used by GEM ioctl or kernel driver to
* set the tiling flags on a buffer.
*/
void amdgpu_bo_get_tiling_flags(struct amdgpu_bo *bo, u64 *tiling_flags)
{
lockdep_assert_held(&bo->tbo.resv->lock.base);
if (tiling_flags)
*tiling_flags = bo->tiling_flags;
}
/**
* amdgpu_bo_set_metadata - set metadata
* @bo: &amdgpu_bo buffer object
* @metadata: new metadata
* @metadata_size: size of the new metadata
* @flags: flags of the new metadata
*
* Sets buffer object's metadata, its size and flags.
* Used via GEM ioctl.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_set_metadata (struct amdgpu_bo *bo, void *metadata,
uint32_t metadata_size, uint64_t flags)
{
void *buffer;
if (!metadata_size) {
if (bo->metadata_size) {
kfree(bo->metadata);
bo->metadata = NULL;
bo->metadata_size = 0;
}
return 0;
}
if (metadata == NULL)
return -EINVAL;
buffer = kmemdup(metadata, metadata_size, GFP_KERNEL);
if (buffer == NULL)
return -ENOMEM;
kfree(bo->metadata);
bo->metadata_flags = flags;
bo->metadata = buffer;
bo->metadata_size = metadata_size;
return 0;
}
/**
* amdgpu_bo_get_metadata - get metadata
* @bo: &amdgpu_bo buffer object
* @buffer: returned metadata
* @buffer_size: size of the buffer
* @metadata_size: size of the returned metadata
* @flags: flags of the returned metadata
*
* Gets buffer object's metadata, its size and flags. buffer_size shall not be
* less than metadata_size.
* Used via GEM ioctl.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_get_metadata(struct amdgpu_bo *bo, void *buffer,
size_t buffer_size, uint32_t *metadata_size,
uint64_t *flags)
{
if (!buffer && !metadata_size)
return -EINVAL;
if (buffer) {
if (buffer_size < bo->metadata_size)
return -EINVAL;
if (bo->metadata_size)
memcpy(buffer, bo->metadata, bo->metadata_size);
}
if (metadata_size)
*metadata_size = bo->metadata_size;
if (flags)
*flags = bo->metadata_flags;
return 0;
}
/**
* amdgpu_bo_move_notify - notification about a memory move
* @bo: pointer to a buffer object
* @evict: if this move is evicting the buffer from the graphics address space
* @new_mem: new information of the bufer object
*
* Marks the corresponding &amdgpu_bo buffer object as invalid, also performs
* bookkeeping.
* TTM driver callback which is called when ttm moves a buffer.
*/
void amdgpu_bo_move_notify(struct ttm_buffer_object *bo,
bool evict,
struct ttm_mem_reg *new_mem)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
struct amdgpu_bo *abo;
struct ttm_mem_reg *old_mem = &bo->mem;
if (!amdgpu_bo_is_amdgpu_bo(bo))
return;
abo = ttm_to_amdgpu_bo(bo);
amdgpu_vm_bo_invalidate(adev, abo, evict);
amdgpu_bo_kunmap(abo);
/* remember the eviction */
if (evict)
atomic64_inc(&adev->num_evictions);
/* update statistics */
if (!new_mem)
return;
/* move_notify is called before move happens */
trace_amdgpu_bo_move(abo, new_mem->mem_type, old_mem->mem_type);
}
/**
* amdgpu_bo_fault_reserve_notify - notification about a memory fault
* @bo: pointer to a buffer object
*
* Notifies the driver we are taking a fault on this BO and have reserved it,
* also performs bookkeeping.
* TTM driver callback for dealing with vm faults.
*
* Returns:
* 0 for success or a negative error code on failure.
*/
int amdgpu_bo_fault_reserve_notify(struct ttm_buffer_object *bo)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
struct ttm_operation_ctx ctx = { false, false };
struct amdgpu_bo *abo;
unsigned long offset, size;
int r;
if (!amdgpu_bo_is_amdgpu_bo(bo))
return 0;
abo = ttm_to_amdgpu_bo(bo);
/* Remember that this BO was accessed by the CPU */
abo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
if (bo->mem.mem_type != TTM_PL_VRAM)
return 0;
size = bo->mem.num_pages << PAGE_SHIFT;
offset = bo->mem.start << PAGE_SHIFT;
if ((offset + size) <= adev->gmc.visible_vram_size)
return 0;
/* Can't move a pinned BO to visible VRAM */
if (abo->pin_count > 0)
return -EINVAL;
/* hurrah the memory is not visible ! */
atomic64_inc(&adev->num_vram_cpu_page_faults);
amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
AMDGPU_GEM_DOMAIN_GTT);
/* Avoid costly evictions; only set GTT as a busy placement */
abo->placement.num_busy_placement = 1;
abo->placement.busy_placement = &abo->placements[1];
r = ttm_bo_validate(bo, &abo->placement, &ctx);
if (unlikely(r != 0))
return r;
offset = bo->mem.start << PAGE_SHIFT;
/* this should never happen */
if (bo->mem.mem_type == TTM_PL_VRAM &&
(offset + size) > adev->gmc.visible_vram_size)
return -EINVAL;
return 0;
}
/**
* amdgpu_bo_fence - add fence to buffer object
*
* @bo: buffer object in question
* @fence: fence to add
* @shared: true if fence should be added shared
*
*/
void amdgpu_bo_fence(struct amdgpu_bo *bo, struct dma_fence *fence,
bool shared)
{
struct reservation_object *resv = bo->tbo.resv;
if (shared)
reservation_object_add_shared_fence(resv, fence);
else
reservation_object_add_excl_fence(resv, fence);
}
/**
* amdgpu_sync_wait_resv - Wait for BO reservation fences
*
* @bo: buffer object
* @owner: fence owner
* @intr: Whether the wait is interruptible
*
* Returns:
* 0 on success, errno otherwise.
*/
int amdgpu_bo_sync_wait(struct amdgpu_bo *bo, void *owner, bool intr)
{
struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
struct amdgpu_sync sync;
int r;
amdgpu_sync_create(&sync);
amdgpu_sync_resv(adev, &sync, bo->tbo.resv, owner, false);
r = amdgpu_sync_wait(&sync, intr);
amdgpu_sync_free(&sync);
return r;
}
/**
* amdgpu_bo_gpu_offset - return GPU offset of bo
* @bo: amdgpu object for which we query the offset
*
* Note: object should either be pinned or reserved when calling this
* function, it might be useful to add check for this for debugging.
*
* Returns:
* current GPU offset of the object.
*/
u64 amdgpu_bo_gpu_offset(struct amdgpu_bo *bo)
{
WARN_ON_ONCE(bo->tbo.mem.mem_type == TTM_PL_SYSTEM);
WARN_ON_ONCE(!ww_mutex_is_locked(&bo->tbo.resv->lock) &&
!bo->pin_count && bo->tbo.type != ttm_bo_type_kernel);
WARN_ON_ONCE(bo->tbo.mem.start == AMDGPU_BO_INVALID_OFFSET);
WARN_ON_ONCE(bo->tbo.mem.mem_type == TTM_PL_VRAM &&
!(bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS));
return amdgpu_gmc_sign_extend(bo->tbo.offset);
}
/**
* amdgpu_bo_get_preferred_pin_domain - get preferred domain for scanout
* @adev: amdgpu device object
* @domain: allowed :ref:`memory domains <amdgpu_memory_domains>`
*
* Returns:
* Which of the allowed domains is preferred for pinning the BO for scanout.
*/
uint32_t amdgpu_bo_get_preferred_pin_domain(struct amdgpu_device *adev,
uint32_t domain)
{
if (domain == (AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT)) {
domain = AMDGPU_GEM_DOMAIN_VRAM;
if (adev->gmc.real_vram_size <= AMDGPU_SG_THRESHOLD)
domain = AMDGPU_GEM_DOMAIN_GTT;
}
return domain;
}
| 26.043671 | 80 | 0.709194 | [
"object"
] |
ec9e99460d61e62d80fb979e7ecf9debe1b3be63 | 3,160 | h | C | third_party/WebKit/Source/platform/audio/AudioProcessor.h | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/WebKit/Source/platform/audio/AudioProcessor.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/WebKit/Source/platform/audio/AudioProcessor.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AudioProcessor_h
#define AudioProcessor_h
#include "platform/PlatformExport.h"
namespace blink {
class AudioBus;
// AudioProcessor is an abstract base class representing an audio signal processing object with a single input and a single output,
// where the number of input channels equals the number of output channels. It can be used as one part of a complex DSP algorithm,
// or as the processor for a basic (one input - one output) AudioNode.
class PLATFORM_EXPORT AudioProcessor {
public:
AudioProcessor(float sampleRate, unsigned numberOfChannels)
: m_initialized(false)
, m_numberOfChannels(numberOfChannels)
, m_sampleRate(sampleRate)
{
}
virtual ~AudioProcessor();
// Full initialization can be done here instead of in the constructor.
virtual void initialize() = 0;
virtual void uninitialize() = 0;
// Processes the source to destination bus. The number of channels must match in source and destination.
virtual void process(const AudioBus* source, AudioBus* destination, size_t framesToProcess) = 0;
// Resets filter state
virtual void reset() = 0;
virtual void setNumberOfChannels(unsigned) = 0;
virtual unsigned numberOfChannels() const = 0;
bool isInitialized() const { return m_initialized; }
float sampleRate() const { return m_sampleRate; }
virtual double tailTime() const = 0;
virtual double latencyTime() const = 0;
protected:
bool m_initialized;
unsigned m_numberOfChannels;
float m_sampleRate;
};
} // namespace blink
#endif // AudioProcessor_h
| 37.619048 | 131 | 0.747152 | [
"object"
] |
eca2ee110a1a40e5367673de901dad1982742d47 | 6,233 | h | C | tms_rc/tms_rc_smartpal/smartpal_control/src/sp5_client.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 54 | 2015-01-06T06:58:28.000Z | 2021-05-02T07:49:37.000Z | tms_rc/tms_rc_smartpal/smartpal_control/src/sp5_client.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 114 | 2015-01-07T06:42:21.000Z | 2022-02-12T05:54:04.000Z | tms_rc/tms_rc_smartpal/smartpal_control/src/sp5_client.h | robotpilot/ros_tms | 3d6b6579e89aa9cb216cd3cb6157fabc553c18f1 | [
"BSD-3-Clause"
] | 24 | 2015-03-27T08:35:59.000Z | 2020-06-08T13:05:31.000Z | //------------------------------------------------------------------------------
#ifndef __CLIENT_H__
#define __CLIENT_H__
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include "idl/sp5/Mobility.hh"
#include "idl/sp5/ArmUnit.hh"
#include "idl/sp5/GripperUnit.hh"
#include "idl/sp5/LumbarUnit.hh"
#define OFF 0
#define ON 1
#define ArmR 0
#define ArmL 1
#define GripperR 0
#define GripperL 1
#define SUCCESS 1
#define FAILURE -1
#define OK 0
#define NG -1
#define STATUS_ERR -2
#define VALUE_ERR -3
#define NOT_SV_ON_ERR -4
#define FULL_MOTION_QUEUE_ERR -5
#define OVER_MAX_VEL_ERR -6
#define OVER_MAX_ACC_ERR -7
#define LOAD_ESTIMATE_ERR -8
#define FULL_COMMAND_ERR -9
#define OVER_MAX_VEL_WARNING -100
#define OVER_MAX_ACC_WARNING -101
#define CORBA_ERR -110
#define RL_ERR -111
#define SRV_UNIT_ERR -112
#define SRV_CMD_ERR -113
#define SRV_UNSUPPORTED_CMD_ERR -114
#define Unpowered 16 // 0x10
#define Powered 17 // 0x11
#define Ready 18 // 0x12
#define Busy 19 // 0x13
#define Paused 20 // 0x14
#define Alarm 21 // 0x15
#define jogBusy 22 // 0x16
#define DirectBusy 23 // 0x17
#define Locked 24 // 0x18
#define Stuck 25 // 0x19
#define Caution 26 // 0x1A
#define VehicleReady 16 // 0x10
#define VehicleBusy 17 // 0x11
#define UNIT_ALL 0
#define UNIT_VEHICLE 1
#define UNIT_ARM_R 2
#define UNIT_ARM_L 3
#define UNIT_GRIPPER_R 4
#define UNIT_GRIPPER_L 5
#define UNIT_LUMBA 6
#define UNIT_CC 7
#define CMD_clearAlarm 0
#define CMD_setPower 1
#define CMD_setServo 2
#define CMD_pause 3
#define CMD_resume 4
#define CMD_abort 5
#define CMD_stop 6
#define CMD_getState 7
#define CMD_getPose 8
#define CMD_move 15
using namespace std;
#define PI 3.14159265
inline double rad2deg(double rad)
{
return (180.0 * rad / (PI));
}
inline double deg2rad(double deg)
{
return (PI * deg / 180.0);
}
class Client
{
public:
Client();
virtual ~Client();
bool Initialize();
bool Shutdown();
//--------------------------------------------------------------------------
// SmartPal Vehicle
int8_t vehicleClearAlarm();
int8_t vehicleSetPower(double OnOff);
int8_t vehicleSetServo(double OnOff);
int8_t vehiclePause();
int8_t vehicleResume();
int8_t vehicleStop();
int8_t vehicleGetState();
int8_t vehicleGetPos(double *x_m, double *y_m, double *theta_rad);
int8_t vehicleSetPos(double x_m, double y_m, double theta_rad);
int8_t vehicleSetVel(double velT_mps, double velR_radps);
int8_t vehicleSetAcc(double accT_mps2, double accR_radps2);
int8_t vehicleMoveLinearAbs(double x_m, double y_m, double theta_rad);
int8_t vehicleMoveLinearRel(double x_m, double y_m, double theta_rad);
int8_t vehicleMoveCruiseAbs(double x_m, double y_m);
int8_t vehicleMoveCruiseRel(double x_m, double y_m);
int8_t vehicleMoveContinuousRel(double x_m, double y_m, double theta_rad);
int8_t vehicleMoveCircularRel(double x_m, double y_m, double angle_rad);
int8_t vehicleSetJogTimeout(double timeout_msec);
int8_t vehicleMoveJog(double vx_mps, double vy_mps, double vt_radps);
//--------------------------------------------------------------------------
// SmartPal Arm
int8_t armReturnValue(int8_t msg);
int8_t armReturnAlarm(int8_t msg);
int8_t armClearAlarm(int8_t RL);
int8_t armSetPower(int8_t RL, double OnOff);
int8_t armSetServo(int8_t RL, double OnOff);
int8_t armPause(int8_t RL);
int8_t armResume(int8_t RL);
int8_t armAbort(int8_t RL);
int8_t armStop(int8_t RL);
int8_t armGetActiveAlarm(int8_t RL, u_int32_t num_request, double *return_code);
int8_t armGetState(int8_t RL);
int8_t armGetPos(int8_t RL, double frameID, double *posdata);
int8_t armSetJointAcc(int8_t RL, double acc_ms);
int8_t armSetLinearAcc(int8_t RL, double accT_ms, double accR_ms);
bool armIsPowerOn(int8_t RL);
bool armIsServoOn(int8_t RL);
int8_t armMoveJointAbs(int8_t RL, double *joint_rad, double vel_radps);
int8_t armMoveJointRel(int8_t RL, double *joint_rad, double vel_radps);
int8_t armMoveLinearAbs(int8_t RL, double cpType, double *cartesianPos, double elbow_rad, double vt_mps,
double vr_radps);
int8_t armMoveLinearRel(int8_t RL, double cpType, double *cartesianPos, double elbow_rad, double vt_mps,
double vr_radps);
int8_t armGetSoftLimit(int8_t RL);
//--------------------------------------------------------------------------
// SmartPal Gripper
int8_t gripperClearAlarm(int8_t RL);
int8_t gripperSetPower(int8_t RL, double OnOff);
int8_t gripperSetServo(int8_t RL, double OnOff);
int8_t gripperPause(int8_t RL);
int8_t gripperResume(int8_t RL);
int8_t gripperAbort(int8_t RL);
int8_t gripperStop(int8_t RL);
int8_t gripperGetState(int8_t RL);
int8_t gripperGetPos(int8_t RL, double *pos_rad);
int8_t gripperMoveAbs(int8_t RL, double j_rad, double vel_radps, double acc_radps2);
//--------------------------------------------------------------------------
// SmartPal Lumba
int8_t lumbaClearAlarm();
int8_t lumbaSetPower(double OnOff);
int8_t lumbaSetServo(double OnOff);
int8_t lumbaPause();
int8_t lumbaResume();
int8_t lumbaAbort();
int8_t lumbaStop();
int8_t lumbaGetState();
int8_t lumbaGetPos(double *low_rad, double *high_rad);
int8_t lumbaMoveCooperative(double z_rad, double vel_radps, double acc_radps2);
int8_t lumbaMove(double low_rad, double high_rad, double vel_radps, double acc_radps2);
int8_t lumbaMoveLowerAxis(double low_rad, double vel_radps, double acc_radps2);
int8_t lumbaMoveUpperAxis(double high_rad, double vel_radps, double acc_radps2);
protected:
CORBA::ORB_var orb;
YeRTUnitMobility::mobility_var CommandObj_Vehicle;
ArmUnit_var CommandObj_ArmR;
ArmUnit_var CommandObj_ArmL;
GripperUnit_var CommandObj_GripperR;
GripperUnit_var CommandObj_GripperL;
LumbarUnit_var CommandObj_Lumbar;
CORBA::Short corbaS1, corbaS2;
CORBA::Double corbaD1, corbaD2, corbaD3, corbaD4, corbaD5, corbaD6;
CORBA::String_var corbaStr1;
CORBA::Boolean corbaB1;
CORBA::Long corbaL1;
CORBA::ULong corbaUL1;
char orb_ip[24];
char orb_port[8];
char context_name[64];
private:
bool bInitialize;
};
#endif // __CLIENT_H__
| 29.966346 | 106 | 0.708968 | [
"vector"
] |
ecaadaa7495598ec0e5f1ba3334e2e0c9af0856c | 6,159 | h | C | hphp/runtime/vm/jit/reg-alloc.h | Majkl578/hhvm | fe70efe4efa8318536ea1d4940362e83e641d905 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/reg-alloc.h | Majkl578/hhvm | fe70efe4efa8318536ea1d4940362e83e641d905 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/vm/jit/reg-alloc.h | Majkl578/hhvm | fe70efe4efa8318536ea1d4940362e83e641d905 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_VM_REG_ALLOC_H_
#define incl_HPHP_VM_REG_ALLOC_H_
#include <vector>
#include "hphp/runtime/vm/jit/ir.h"
#include "hphp/runtime/vm/jit/phys-reg.h"
#include "hphp/runtime/vm/jit/state-vector.h"
#include "hphp/runtime/vm/jit/translator-runtime.h"
#ifdef VOID
#undef VOID
#endif
namespace HPHP { namespace jit {
class IRUnit;
inline bool isI32(int64_t c) { return c == int32_t(c); }
inline bool isU32(int64_t c) { return c == uint32_t(c); }
// This value must be consistent with the number of pre-allocated
// bytes for spill locations in __enterTCHelper in mc-generator.cpp.
// Be careful when changing this value.
const size_t NumPreAllocatedSpillLocs = kReservedRSPSpillSpace /
sizeof(uint64_t);
struct RegAllocInfo {
struct RegMap {
// new way
PhysLoc& src(unsigned i) {
assert(i < m_dstOff);
return at(i);
}
PhysLoc& dst(unsigned i) { return at(i + m_dstOff); }
const PhysLoc& src(unsigned i) const {
assert(i < m_dstOff);
return at(i);
}
const PhysLoc& dst(unsigned i) const { return at(i + m_dstOff); }
void resize(unsigned n) const {
m_dstOff = n;
m_locs.resize(n);
}
private:
PhysLoc& at(unsigned i) {
assert(i < m_locs.size());
return m_locs[i];
}
const PhysLoc& at(unsigned i) const {
assert(i < m_locs.size());
return m_locs[i];
}
friend struct RegAllocInfo;
RegMap& init(const IRInstruction* inst) const {
if (m_locs.empty()) {
m_dstOff = inst->numSrcs();
m_locs.resize(inst->numSrcs() + inst->numDsts());
}
return *const_cast<RegMap*>(this);
}
private:
mutable unsigned m_dstOff { 0 };
mutable jit::vector<PhysLoc> m_locs;
};
explicit RegAllocInfo(const IRUnit& unit) : m_regs(unit, RegMap()) {}
RegAllocInfo(const RegAllocInfo& other) : m_regs(other.m_regs) {}
RegAllocInfo(RegAllocInfo&& other) noexcept : m_regs(other.m_regs) {}
RegMap& operator[](const IRInstruction* i) { return m_regs[i].init(i); }
RegMap& operator[](const IRInstruction& i) { return m_regs[i].init(&i); }
const RegMap& operator[](const IRInstruction* i) const {
return m_regs[i].init(i);
}
const RegMap& operator[](const IRInstruction& i) const {
return m_regs[i].init(&i);
}
RegSet srcRegs(const IRInstruction& inst) const {
auto regs = RegSet();
auto& map = m_regs[inst];
for (unsigned i = 0, n = inst.numSrcs(); i < n; ++i) {
regs |= map.src(i).regs();
}
return regs;
}
RegSet dstRegs(const IRInstruction& inst) const {
auto regs = RegSet();
if (inst.is(Shuffle)) {
for (auto const& dest : *inst.extra<Shuffle>()) {
regs |= dest.regs();
}
} else {
auto& map = m_regs[inst];
for (unsigned i = 0, n = inst.numDsts(); i < n; ++i) {
regs |= map.dst(i).regs();
}
}
return regs;
}
private:
StateVector<IRInstruction,RegMap> m_regs;
};
/*
* New register allocator doing extended linear scan
*/
RegAllocInfo allocateRegs(IRUnit&);
/*
* A Constraint represents a set of locations an operand may
* be assigned to by the register allocator. GP and SIMD are
* self explanitory. VOID means no-location, i.e. InvalidReg.
* Only some instructions allow a VOID destination, so VOID
* is explicit.
*/
struct Constraint {
enum Mask: uint8_t {
GP = 1,
SIMD = 2,
VOID = 4, // used for unused dests that can be InvalidReg
IMM = 8
};
/* implicit */ Constraint(Mask m)
: m_mask(m)
, m_reg(InvalidReg)
{}
/* implicit */ Constraint(PhysReg r)
: m_mask(maskFromReg(r))
, m_reg(r)
{}
Constraint& operator=(Constraint c2) {
m_mask = c2.m_mask;
m_reg = c2.m_reg;
return *this;
}
bool operator==(Constraint c2) const {
return m_mask == c2.m_mask && m_reg == c2.m_reg;
}
bool operator!=(Constraint c2) const {
return !(*this == c2);
}
PhysReg reg() const { return m_reg; }
Constraint operator|(Constraint c2) const {
return (*this == c2) ? *this :
Constraint(Mask(m_mask | c2.m_mask));
}
Constraint operator&(Constraint c2) const {
return (*this == c2) ? *this :
Constraint(Mask(m_mask & c2.m_mask));
}
Constraint operator-(Constraint c2) const {
assert(m_reg == InvalidReg && c2.m_reg == InvalidReg);
return Mask(m_mask & ~c2.m_mask);
}
Constraint& operator|=(Constraint c2) { return *this = *this | c2; }
Constraint& operator&=(Constraint c2) { return *this = *this & c2; }
Constraint& operator-=(Constraint c2) { return *this = *this - c2; }
explicit operator bool() const { return m_mask != 0; }
private:
static Mask maskFromReg(PhysReg r) {
return r.isGP() ? GP : r.isSIMD() ? SIMD : VOID;
}
private:
Mask m_mask;
PhysReg m_reg; // if valid, force this register
};
/*
* return a constraint for the given src
*/
Constraint srcConstraint(const IRInstruction& inst, unsigned src);
/*
* Return a constraint for the given destination.
*/
Constraint dstConstraint(const IRInstruction& inst, unsigned dst);
PhysReg forceAlloc(const SSATmp& tmp);
}}
#endif
| 28.915493 | 75 | 0.593765 | [
"vector"
] |
ecac5841e38b7c2a8b17c5502067f621087732ca | 4,154 | h | C | resources/home/dnanexus/root/include/RooStats/HLFactory.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/RooStats/HLFactory.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/RooStats/HLFactory.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | // @(#)root/roostats:$Id$
/*************************************************************************
* Project: RooStats *
* Package: RooFit/RooStats *
* Authors: *
* Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke *
*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef RooStats_HLFactory
#define RooStats_HLFactory
#include "TString.h"
#include "RooAbsPdf.h"
#include "RooCategory.h"
#include "RooDataSet.h"
#include "RooWorkspace.h"
// class TString;
// class RooDataSet;
namespace RooStats {
class HLFactory : public TNamed {
public:
/// Constructor
HLFactory(const char *name,
const char *fileName=0,
bool isVerbose = false);
/// Constructor with external RooWorkspace
HLFactory(const char* name,
RooWorkspace* externalWs,
bool isVerbose = false);
/// Default Constructor
HLFactory();
/// Default Destructor
~HLFactory();
/// Add channel for the combination
int AddChannel(const char* label,
const char* SigBkgPdfName,
const char* BkgPdfName=0,
const char* datasetName=0);
/// Dump the Workspace content as configuration file
/* It needs some workspace object list or something..*/
void DumpCfg(const char* /*cardname*/ ){ /* t.b.i. */ }; // Dump the factory content as configuration file
/// Get the combined signal plus background pdf
RooAbsPdf* GetTotSigBkgPdf(); // Get the Signal and Background combined model
/// Get the combined background pdf
RooAbsPdf* GetTotBkgPdf(); // Get the Background combined model
/// Get the combined dataset
RooDataSet* GetTotDataSet(); // Get the combined dataset
/// Get the combined dataset
RooCategory* GetTotCategory(); // Get the category
/// Get the RooWorkspace containing the models and variables
RooWorkspace* GetWs(){return fWs;}; // Expose the internal Workspace
/// Process a configuration file
int ProcessCard(const char* filename);
private:
/// The category of the combination
RooCategory* fComboCat;
/// The background model combination
RooAbsPdf* fComboBkgPdf;
/// The signal plus background model combination
RooAbsPdf* fComboSigBkgPdf;
/// The datasets combination
RooDataSet* fComboDataset;
/// Flag to keep trace of the status of the combination
bool fCombinationDone;
/// Create the category for the combinations
void fCreateCategory();
/// Check the length of the lists
bool fNamesListsConsistent();
/// List of channels names to combine for the signal plus background pdfs
TList fSigBkgPdfNames;
/// List of channels names to combine for the background pdfs
TList fBkgPdfNames;
/// List of channels names to combine for the datasets
TList fDatasetsNames;
/// List of channels names to combine for the datasets
TList fLabelsNames;
/// The verbosity flag
bool fVerbose;
/// Keep trace of the inclusion deepness
int fInclusionLevel;
/// The RooWorkspace containing the models and variables
RooWorkspace* fWs;
/// Owns workspace
bool fOwnWs;
/// Read the actual cfg file
int fReadFile(const char*fileName, bool is_included = false);
/// Parse a single line an puts the content in the RooWorkSpace
int fParseLine(TString& line);
ClassDef(HLFactory,1) // The high Level Model Factory to create models from datacards
};
}
#endif
| 29.884892 | 111 | 0.584978 | [
"object",
"model"
] |
ecb44f2c750d3845f27f7f08f49008f9d3fbcab9 | 6,093 | h | C | Modules/Core/Common/include/itkImageBoundaryCondition.h | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2021-11-29T14:41:43.000Z | 2021-11-29T14:41:43.000Z | Modules/Core/Common/include/itkImageBoundaryCondition.h | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2017-08-18T19:28:52.000Z | 2017-08-18T19:28:52.000Z | Modules/Core/Common/include/itkImageBoundaryCondition.h | floryst/ITK | 321e673bcbac15aae2fcad863fd0977b7fbdb3e9 | [
"Apache-2.0"
] | 1 | 2017-08-18T19:07:39.000Z | 2017-08-18T19:07:39.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkImageBoundaryCondition_h
#define itkImageBoundaryCondition_h
#include "itkIndex.h"
#include "itkNeighborhood.h"
#include "itkImageRegion.h"
namespace itk
{
/**
*\class ImageBoundaryCondition
* \brief A virtual base object that defines an interface to a class of
* boundary condition objects for use by neighborhood iterators.
*
* A boundary condition object supplies a phantom pixel value when
* given a neighborhood of (pointers to) image values, the (ND) index of
* the phantom pixel, and its (ND) offset from the boundary. The index
* of the phantom pixel is relative to the "upper left-hand corner" of
* the neighborhood (as opposed to its center).
*
*
* Associated Types Description
* ---------------- -----------
* PixelType The data type of the return value.
* PixelPointerType A pointer to PixelType.
* PixelPointerTypeNeighborhood A neighborhood of PixelPointerTypes
* that points to the pixel values in
* an image neighborhood.
*
* \ingroup DataRepresentation
* \ingroup ImageObjects
* \ingroup ITKCommon
*/
template< typename TInputImage, typename TOutputImage = TInputImage >
class ITK_TEMPLATE_EXPORT ImageBoundaryCondition
{
public:
/** Extract information from the image type */
static constexpr unsigned int ImageDimension = TInputImage::ImageDimension;
/** Standard type alias. */
using Self = ImageBoundaryCondition;
/** Extract information from the image type */
using InputImageType = TInputImage;
using OutputImageType = TOutputImage;
using PixelType = typename TInputImage::PixelType;
using PixelPointerType = typename TInputImage::InternalPixelType *;
using OutputPixelType = typename TOutputImage::PixelType;
using IndexType = Index< ImageDimension >;
using SizeType = Size< ImageDimension >;
using OffsetType = Offset< ImageDimension >;
using RegionType = ImageRegion< ImageDimension >;
/** Type of the data container passed to this function object. */
using NeighborhoodType = Neighborhood< PixelPointerType, ImageDimension >;
/** Functor used to access pixels from a neighborhood of pixel pointers */
using NeighborhoodAccessorFunctorType = typename TInputImage::NeighborhoodAccessorFunctorType;
/** Default constructor. */
ImageBoundaryCondition() = default;
/** Runtime information support. */
virtual const char * GetNameOfClass() const
{
return "itkImageBoundaryCondition";
}
/** Utility for printing the boundary condition. */
virtual void Print( std::ostream & os, Indent i = 0 ) const
{
os << i << this->GetNameOfClass() << " (" << this << ")" << std::endl;
}
/** Returns a value for a given out-of-bounds pixel. The arguments are the
* phantom pixel (ND) index within the neighborhood, the pixel's offset from
* the nearest image border pixel, and a neighborhood of pointers to pixel
* values in the image. */
virtual OutputPixelType operator()(const OffsetType & point_index,
const OffsetType & boundary_offset,
const NeighborhoodType *data) const = 0;
/** Computes and returns the appropriate pixel value from
* neighborhood iterator data, using the functor. */
virtual OutputPixelType operator()(
const OffsetType & point_index,
const OffsetType & boundary_offset,
const NeighborhoodType *data,
const NeighborhoodAccessorFunctorType & neighborhoodAccessorFunctor) const = 0;
virtual ~ImageBoundaryCondition() = default;
/** Tell if the boundary condition can index to any location within
* the associated iterator's neighborhood or if it has some limited
* subset (such as none) that it relies upon.
* Subclasses should override this method if they can safely limit
* indexes to active pixels (or no pixels).
*/
virtual bool RequiresCompleteNeighborhood() { return true; }
/** Determines the necessary input region for an output region given
* the largest possible region of the input image. Subclasses should
* override this method to efficiently support streaming.
*
* \param inputLargestPossibleRegion Largest possible region of the input image.
* \param outputRequestedRegion The output requested region.
* \return The necessary input region required to determine the
* pixel values in the outputRequestedRegion.
*/
virtual RegionType GetInputRequestedRegion( const RegionType & inputLargestPossibleRegion,
const RegionType & outputRequestedRegion ) const
{
(void) outputRequestedRegion;
return inputLargestPossibleRegion;
}
/** Returns a value for a given pixel at an index. If the index is inside the
* bounds of the input image, then the pixel value is obtained from
* the input image. Otherwise, the pixel value is determined
* according to the boundary condition type.
*
* \param index The index of the desired pixel.
* \param image The image from which pixel values should be determined.
*/
virtual OutputPixelType GetPixel( const IndexType & index,
const TInputImage * image ) const = 0;
};
} // end namespace itk
#endif
| 40.62 | 96 | 0.686197 | [
"object"
] |
ecbbc3a63714acd77addaf60b28bf2ea721cfe54 | 18,861 | c | C | gst/elements/gvaclassify/gstgvaclassify.c | TolyaTalamanov/gst-video-analytics | 7b3d74b9887911eaedbe8cad9ce4af64174d6568 | [
"MIT"
] | null | null | null | gst/elements/gvaclassify/gstgvaclassify.c | TolyaTalamanov/gst-video-analytics | 7b3d74b9887911eaedbe8cad9ce4af64174d6568 | [
"MIT"
] | null | null | null | gst/elements/gvaclassify/gstgvaclassify.c | TolyaTalamanov/gst-video-analytics | 7b3d74b9887911eaedbe8cad9ce4af64174d6568 | [
"MIT"
] | 1 | 2019-03-19T08:28:11.000Z | 2019-03-19T08:28:11.000Z | /*******************************************************************************
* Copyright (C) <2018-2019> Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#include "gstgvaclassify.h"
#include <gst/base/gstbasetransform.h>
#include <gst/gst.h>
#include <gst/video/video.h>
#include "config.h"
#define UNUSED(x) (void)(x)
#define ELEMENT_LONG_NAME "Object classification (requires GstVideoRegionOfInterestMeta on input)"
#define ELEMENT_DESCRIPTION "Object classification (requires GstVideoRegionOfInterestMeta on input)"
GST_DEBUG_CATEGORY_STATIC(gst_gva_classify_debug_category);
#define GST_CAT_DEFAULT gst_gva_classify_debug_category
#define DEFAULT_MODEL NULL
#define DEFAULT_INFERENCE_ID NULL
#define DEFAULT_MODEL_PROC NULL
#define DEFAULT_OBJECT_CLASS ""
#define DEFAULT_DEVICE "CPU"
#define DEFAULT_META_FORMAT ""
#define DEFAULT_CPU_EXTENSION ""
#define DEFAULT_GPU_EXTENSION ""
#define DEFAULT_RESIZE_BY_INFERENCE FALSE
#define DEFAULT_MIN_BATCH_SIZE 1
#define DEFAULT_MAX_BATCH_SIZE 1024
#define DEFAULT_BATCH_SIZE 1
#define DEFALUT_MIN_THRESHOLD 0.
#define DEFALUT_MAX_THRESHOLD 1.
#define DEFALUT_THRESHOLD 0.5
#define DEFAULT_MIN_EVERY_NTH_FRAME 1
#define DEFAULT_MAX_EVERY_NTH_FRAME UINT_MAX
#define DEFAULT_EVERY_NTH_FRAME 1
#define DEFAULT_MIN_NIREQ 1
#define DEFAULT_MAX_NIREQ 64
#define DEFAULT_NIREQ 2
#define DEFAULT_CPU_STREAMS ""
#define DEFAULT_USE_LANDMARKS FALSE
static void gst_gva_classify_set_property(GObject *object, guint property_id, const GValue *value, GParamSpec *pspec);
static void gst_gva_classify_get_property(GObject *object, guint property_id, GValue *value, GParamSpec *pspec);
static void gst_gva_classify_dispose(GObject *object);
static void gst_gva_classify_finalize(GObject *object);
static gboolean gst_gva_classify_set_caps(GstBaseTransform *trans, GstCaps *incaps, GstCaps *outcaps);
static gboolean gst_gva_classify_start(GstBaseTransform *trans);
static gboolean gst_gva_classify_stop(GstBaseTransform *trans);
static gboolean gst_gva_classify_sink_event(GstBaseTransform *trans, GstEvent *event);
static GstFlowReturn gst_gva_classify_transform_ip(GstBaseTransform *trans, GstBuffer *buf);
static void gst_gva_classify_cleanup(GstGvaClassify *gvaclassify);
static void gst_gva_classify_reset(GstGvaClassify *gvaclassify);
static GstStateChangeReturn gst_gva_classify_change_state(GstElement *element, GstStateChange transition);
enum {
PROP_0,
PROP_MODEL,
PROP_OBJECT_CLASS,
PROP_DEVICE,
PROP_BATCH_SIZE,
PROP_EVERY_NTH_FRAME,
PROP_NIREQ,
PROP_CPU_EXTENSION,
PROP_GPU_EXTENSION,
PROP_INFERENCE_ID,
PROP_MODEL_PROC,
PROP_CPU_STREAMS,
PROP_USE_LANDMARKS
};
#ifdef SUPPORT_DMA_BUFFER
#define DMA_BUFFER_CAPS GST_VIDEO_CAPS_MAKE_WITH_FEATURES("memory:DMABuf", "{ I420 }") "; "
#else
#define DMA_BUFFER_CAPS
#endif
#ifndef DISABLE_VAAPI
#define VA_SURFACE_CAPS GST_VIDEO_CAPS_MAKE_WITH_FEATURES("memory:VASurface", "{ NV12 }") "; "
#else
#define VA_SURFACE_CAPS
#endif
#define SYSTEM_MEM_CAPS GST_VIDEO_CAPS_MAKE("{ BGRx, BGRA }")
#define INFERENCE_CAPS DMA_BUFFER_CAPS VA_SURFACE_CAPS SYSTEM_MEM_CAPS
#define VIDEO_SINK_CAPS INFERENCE_CAPS
#define VIDEO_SRC_CAPS INFERENCE_CAPS
/* class initialization */
G_DEFINE_TYPE_WITH_CODE(GstGvaClassify, gst_gva_classify, GST_TYPE_BASE_TRANSFORM,
GST_DEBUG_CATEGORY_INIT(gst_gva_classify_debug_category, "gvaclassify", 0,
"debug category for gvaclassify element"));
static void gst_gva_classify_class_init(GstGvaClassifyClass *klass) {
GObjectClass *gobject_class = G_OBJECT_CLASS(klass);
GstBaseTransformClass *base_transform_class = GST_BASE_TRANSFORM_CLASS(klass);
GstElementClass *element_class = GST_ELEMENT_CLASS(klass);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template(
element_class, gst_pad_template_new("src", GST_PAD_SRC, GST_PAD_ALWAYS, gst_caps_from_string(VIDEO_SRC_CAPS)));
gst_element_class_add_pad_template(element_class, gst_pad_template_new("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
gst_caps_from_string(VIDEO_SINK_CAPS)));
gst_element_class_set_static_metadata(element_class, ELEMENT_LONG_NAME, "Video", ELEMENT_DESCRIPTION,
"Intel Corporation");
gobject_class->set_property = gst_gva_classify_set_property;
gobject_class->get_property = gst_gva_classify_get_property;
gobject_class->dispose = gst_gva_classify_dispose;
gobject_class->finalize = gst_gva_classify_finalize;
base_transform_class->set_caps = GST_DEBUG_FUNCPTR(gst_gva_classify_set_caps);
base_transform_class->start = GST_DEBUG_FUNCPTR(gst_gva_classify_start);
base_transform_class->stop = GST_DEBUG_FUNCPTR(gst_gva_classify_stop);
base_transform_class->sink_event = GST_DEBUG_FUNCPTR(gst_gva_classify_sink_event);
base_transform_class->transform_ip = GST_DEBUG_FUNCPTR(gst_gva_classify_transform_ip);
element_class->change_state = GST_DEBUG_FUNCPTR(gst_gva_classify_change_state);
g_object_class_install_property(gobject_class, PROP_MODEL,
g_param_spec_string("model", "Model", "Inference model file path", DEFAULT_MODEL,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(
gobject_class, PROP_INFERENCE_ID,
g_param_spec_string("inference-id", "Inference Id",
"Id for the inference engine to be shared between ovino plugin instances",
DEFAULT_INFERENCE_ID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(
gobject_class, PROP_MODEL_PROC,
g_param_spec_string("model-proc", "Model preproc and postproc",
"JSON file with description of input/output layers pre-processing/post-processing",
DEFAULT_MODEL_PROC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_OBJECT_CLASS,
g_param_spec_string("object-class", "ObjectClass", "Object class",
DEFAULT_OBJECT_CLASS,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_DEVICE,
g_param_spec_string("device", "Device", "Inference device plugin CPU or GPU",
DEFAULT_DEVICE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_CPU_EXTENSION,
g_param_spec_string("cpu-extension", "CpuExtension", "Inference CPU extension",
DEFAULT_CPU_EXTENSION,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_GPU_EXTENSION,
g_param_spec_string("gpu-extension", "GpuExtension", "Inference GPU extension",
DEFAULT_GPU_EXTENSION,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_BATCH_SIZE,
g_param_spec_uint("batch-size", "Batch size", "number frames for batching",
DEFAULT_MIN_BATCH_SIZE, DEFAULT_MAX_BATCH_SIZE,
DEFAULT_BATCH_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_EVERY_NTH_FRAME,
g_param_spec_uint("every-nth-frame", "EveryNthFrame", "Every Nth frame",
DEFAULT_MIN_EVERY_NTH_FRAME, DEFAULT_MAX_EVERY_NTH_FRAME,
DEFAULT_EVERY_NTH_FRAME,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(gobject_class, PROP_NIREQ,
g_param_spec_uint("nireq", "NIReq", "number of inference requests",
DEFAULT_MIN_NIREQ, DEFAULT_MAX_NIREQ, DEFAULT_NIREQ,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(
gobject_class, PROP_USE_LANDMARKS,
g_param_spec_boolean("use-landmarks", "landmarks usage flag", "Controls landmark usage preprocessing stage",
DEFAULT_USE_LANDMARKS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property(
gobject_class, PROP_CPU_STREAMS,
g_param_spec_string("cpu-streams", "CPU-Streams",
"Use multiple inference streams/instances for better parallelization and affinity on CPU",
DEFAULT_CPU_STREAMS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
}
static void gst_gva_classify_cleanup(GstGvaClassify *gvaclassify) {
if (gvaclassify == NULL)
return;
GST_DEBUG_OBJECT(gvaclassify, "gst_gva_classify_cleanup");
if (gvaclassify->inference) {
release_classify_inference(gvaclassify);
gvaclassify->inference = NULL;
}
g_free(gvaclassify->model);
gvaclassify->model = NULL;
g_free(gvaclassify->object_class);
gvaclassify->device = NULL;
g_free(gvaclassify->device);
gvaclassify->device = NULL;
g_free(gvaclassify->model_proc);
gvaclassify->model_proc = NULL;
g_free(gvaclassify->cpu_extension);
gvaclassify->cpu_extension = NULL;
g_free(gvaclassify->gpu_extension);
gvaclassify->gpu_extension = NULL;
g_free(gvaclassify->inference_id);
gvaclassify->inference_id = NULL;
if (gvaclassify->info) {
gst_video_info_free(gvaclassify->info);
gvaclassify->info = NULL;
}
gvaclassify->initialized = FALSE;
}
static void gst_gva_classify_reset(GstGvaClassify *gvaclassify) {
GST_DEBUG_OBJECT(gvaclassify, "gst_gva_classify_reset");
if (gvaclassify == NULL)
return;
gst_gva_classify_cleanup(gvaclassify);
gvaclassify->model = g_strdup(DEFAULT_MODEL);
gvaclassify->object_class = g_strdup(DEFAULT_OBJECT_CLASS);
gvaclassify->device = g_strdup(DEFAULT_DEVICE);
gvaclassify->model_proc = g_strdup(DEFAULT_MODEL_PROC);
gvaclassify->batch_size = DEFAULT_BATCH_SIZE;
gvaclassify->every_nth_frame = DEFAULT_EVERY_NTH_FRAME;
gvaclassify->nireq = DEFAULT_NIREQ;
gvaclassify->cpu_extension = g_strdup(DEFAULT_CPU_EXTENSION);
gvaclassify->gpu_extension = g_strdup(DEFAULT_GPU_EXTENSION);
gvaclassify->inference_id = g_strdup(DEFAULT_INFERENCE_ID);
gvaclassify->cpu_streams = DEFAULT_CPU_STREAMS;
gvaclassify->inference = NULL;
gvaclassify->initialized = FALSE;
gvaclassify->info = NULL;
gvaclassify->use_landmarks = DEFAULT_USE_LANDMARKS;
}
static GstStateChangeReturn gst_gva_classify_change_state(GstElement *element, GstStateChange transition) {
GstStateChangeReturn ret;
GstGvaClassify *gvaclassify;
gvaclassify = GST_GVA_CLASSIFY(element);
GST_DEBUG_OBJECT(gvaclassify, "gst_gva_classify_change_state");
ret = GST_ELEMENT_CLASS(gst_gva_classify_parent_class)->change_state(element, transition);
switch (transition) {
case GST_STATE_CHANGE_READY_TO_NULL: {
gst_gva_classify_reset(gvaclassify);
break;
}
default:
break;
}
return ret;
}
static void gst_gva_classify_init(GstGvaClassify *gvaclassify) {
GST_DEBUG_OBJECT(gvaclassify, "gst_gva_classify_init");
GST_DEBUG_OBJECT(gvaclassify, "%s", GST_ELEMENT_NAME(GST_ELEMENT(gvaclassify)));
gst_gva_classify_reset(gvaclassify);
}
void gst_gva_classify_set_property(GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(object);
GST_DEBUG_OBJECT(gvaclassify, "set_property");
switch (property_id) {
case PROP_MODEL:
gvaclassify->model = g_value_dup_string(value);
break;
case PROP_OBJECT_CLASS:
gvaclassify->object_class = g_value_dup_string(value);
break;
case PROP_DEVICE:
gvaclassify->device = g_value_dup_string(value);
break;
case PROP_MODEL_PROC:
gvaclassify->model_proc = g_value_dup_string(value);
break;
case PROP_BATCH_SIZE:
gvaclassify->batch_size = g_value_get_uint(value);
break;
case PROP_EVERY_NTH_FRAME:
gvaclassify->every_nth_frame = g_value_get_uint(value);
break;
case PROP_NIREQ:
gvaclassify->nireq = g_value_get_uint(value);
break;
case PROP_CPU_EXTENSION:
gvaclassify->cpu_extension = g_value_dup_string(value);
break;
case PROP_GPU_EXTENSION:
gvaclassify->gpu_extension = g_value_dup_string(value);
break;
case PROP_INFERENCE_ID:
gvaclassify->inference_id = g_value_dup_string(value);
break;
case PROP_CPU_STREAMS:
gvaclassify->cpu_streams = g_value_dup_string(value);
break;
case PROP_USE_LANDMARKS:
gvaclassify->use_landmarks = g_value_get_boolean(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
break;
}
}
void gst_gva_classify_get_property(GObject *object, guint property_id, GValue *value, GParamSpec *pspec) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(object);
GST_DEBUG_OBJECT(gvaclassify, "get_property");
switch (property_id) {
case PROP_MODEL:
g_value_set_string(value, gvaclassify->model);
break;
case PROP_OBJECT_CLASS:
g_value_set_string(value, gvaclassify->object_class);
break;
case PROP_DEVICE:
g_value_set_string(value, gvaclassify->device);
break;
case PROP_MODEL_PROC:
g_value_set_string(value, gvaclassify->model_proc);
break;
case PROP_BATCH_SIZE:
g_value_set_uint(value, gvaclassify->batch_size);
break;
case PROP_EVERY_NTH_FRAME:
g_value_set_uint(value, gvaclassify->every_nth_frame);
break;
case PROP_NIREQ:
g_value_set_uint(value, gvaclassify->nireq);
break;
case PROP_CPU_EXTENSION:
g_value_set_string(value, gvaclassify->cpu_extension);
break;
case PROP_GPU_EXTENSION:
g_value_set_string(value, gvaclassify->gpu_extension);
break;
case PROP_INFERENCE_ID:
g_value_set_string(value, gvaclassify->inference_id);
break;
case PROP_CPU_STREAMS:
g_value_set_string(value, gvaclassify->cpu_streams);
break;
case PROP_USE_LANDMARKS:
g_value_set_boolean(value, gvaclassify->use_landmarks);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
break;
}
}
void gst_gva_classify_dispose(GObject *object) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(object);
GST_DEBUG_OBJECT(gvaclassify, "dispose");
/* clean up as possible. may be called multiple times */
G_OBJECT_CLASS(gst_gva_classify_parent_class)->dispose(object);
}
void gst_gva_classify_finalize(GObject *object) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(object);
GST_DEBUG_OBJECT(gvaclassify, "finalize");
/* clean up object here */
gst_gva_classify_cleanup(gvaclassify);
G_OBJECT_CLASS(gst_gva_classify_parent_class)->finalize(object);
}
static gboolean gst_gva_classify_set_caps(GstBaseTransform *trans, GstCaps *incaps, GstCaps *outcaps) {
UNUSED(outcaps);
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(trans);
GST_DEBUG_OBJECT(gvaclassify, "set_caps");
if (!gvaclassify->info) {
gvaclassify->info = gst_video_info_new();
}
gst_video_info_from_caps(gvaclassify->info, incaps);
return TRUE;
}
/* states */
static gboolean gst_gva_classify_start(GstBaseTransform *trans) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(trans);
GST_DEBUG_OBJECT(gvaclassify, "start");
if (gvaclassify->initialized)
goto exit;
if (!gvaclassify->inference_id) {
gvaclassify->inference_id = g_strdup(GST_ELEMENT_NAME(GST_ELEMENT(gvaclassify)));
}
GError *error = NULL;
gvaclassify->inference = aquire_classify_inference(gvaclassify, &error);
if (error) {
GST_ELEMENT_ERROR(gvaclassify, RESOURCE, TOO_LAZY, ("gvaclassify plugin intitialization failed"),
("%s", error->message));
g_error_free(error);
goto exit;
}
gvaclassify->initialized = TRUE;
exit:
return gvaclassify->initialized;
}
static gboolean gst_gva_classify_stop(GstBaseTransform *trans) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(trans);
GST_DEBUG_OBJECT(gvaclassify, "stop");
// FIXME: Hangs when multichannel
// flush_inference_classify(gvaclassify);
return TRUE;
}
static gboolean gst_gva_classify_sink_event(GstBaseTransform *trans, GstEvent *event) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(trans);
GST_DEBUG_OBJECT(gvaclassify, "sink_event");
classify_inference_sink_event(gvaclassify, event);
return GST_BASE_TRANSFORM_CLASS(gst_gva_classify_parent_class)->sink_event(trans, event);
}
static GstFlowReturn gst_gva_classify_transform_ip(GstBaseTransform *trans, GstBuffer *buf) {
GstGvaClassify *gvaclassify = GST_GVA_CLASSIFY(trans);
GST_DEBUG_OBJECT(gvaclassify, "transform_ip");
if (!gvaclassify->inference->instance) { // TODO find a way to move this check out to initialization stage
GST_ELEMENT_ERROR(gvaclassify, RESOURCE, SETTINGS,
("There is no master element provided for gvaclassify elements with inference-id '%s'. At "
"least one element for each inference-id should have model path specified",
gvaclassify->inference_id),
(NULL));
return GST_FLOW_ERROR;
}
return frame_to_classify_inference(gvaclassify, trans, buf, gvaclassify->info);
/* return GST_FLOW_OK; FIXME shouldn't signal about dropping frames in inplace transform function*/
}
| 38.570552 | 119 | 0.694131 | [
"object",
"model",
"transform"
] |
ecbfd5c7c851f1928417abd05883daed1ff89ec2 | 40,038 | c | C | source/blender/editors/space_view3d/drawmesh.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | source/blender/editors/space_view3d/drawmesh.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | source/blender/editors/space_view3d/drawmesh.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* Contributor(s): Blender Foundation, full update, glsl support
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/editors/space_view3d/drawmesh.c
* \ingroup spview3d
*/
#include <string.h>
#include <math.h>
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
#include "BLI_bitmap.h"
#include "BLI_math.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_property_types.h"
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "DNA_view3d_types.h"
#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_material.h"
#include "BKE_paint.h"
#include "BKE_property.h"
#include "BKE_editmesh.h"
#include "BKE_scene.h"
#include "BIF_gl.h"
#include "BIF_glutil.h"
#include "UI_resources.h"
#include "GPU_draw.h"
#include "GPU_material.h"
#include "GPU_basic_shader.h"
#include "GPU_shader.h"
#include "RE_engine.h"
#include "ED_uvedit.h"
#include "view3d_intern.h" /* own include */
/* user data structures for derived mesh callbacks */
typedef struct drawMeshFaceSelect_userData {
Mesh *me;
BLI_bitmap *edge_flags; /* pairs of edge options (visible, select) */
} drawMeshFaceSelect_userData;
typedef struct drawEMTFMapped_userData {
BMEditMesh *em;
bool has_mcol;
int cd_poly_tex_offset;
const MPoly *mpoly;
const MTexPoly *mtexpoly;
} drawEMTFMapped_userData;
typedef struct drawTFace_userData {
const Mesh *me;
const MPoly *mpoly;
const MTexPoly *mtexpoly;
} drawTFace_userData;
/**************************** Face Select Mode *******************************/
/* mainly to be less confusing */
BLI_INLINE int edge_vis_index(const int index) { return index * 2; }
BLI_INLINE int edge_sel_index(const int index) { return index * 2 + 1; }
static BLI_bitmap *get_tface_mesh_marked_edge_info(Mesh *me, bool draw_select_edges)
{
BLI_bitmap *bitmap_edge_flags = BLI_BITMAP_NEW(me->totedge * 2, __func__);
MPoly *mp;
MLoop *ml;
int i, j;
bool select_set;
for (i = 0; i < me->totpoly; i++) {
mp = &me->mpoly[i];
if (!(mp->flag & ME_HIDE)) {
select_set = (mp->flag & ME_FACE_SEL) != 0;
ml = me->mloop + mp->loopstart;
for (j = 0; j < mp->totloop; j++, ml++) {
if ((draw_select_edges == false) &&
(select_set && BLI_BITMAP_TEST(bitmap_edge_flags, edge_sel_index(ml->e))))
{
BLI_BITMAP_DISABLE(bitmap_edge_flags, edge_vis_index(ml->e));
}
else {
BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_vis_index(ml->e));
if (select_set) {
BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_sel_index(ml->e));
}
}
}
}
}
return bitmap_edge_flags;
}
static DMDrawOption draw_mesh_face_select__setHiddenOpts(void *userData, int index)
{
drawMeshFaceSelect_userData *data = userData;
Mesh *me = data->me;
if (me->drawflag & ME_DRAWEDGES) {
if ((BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))))
return DM_DRAW_OPTION_NORMAL;
else
return DM_DRAW_OPTION_SKIP;
}
else if (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index)))
{
return DM_DRAW_OPTION_NORMAL;
}
else {
return DM_DRAW_OPTION_SKIP;
}
}
static DMDrawOption draw_mesh_face_select__setSelectOpts(void *userData, int index)
{
drawMeshFaceSelect_userData *data = userData;
return (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))) ? DM_DRAW_OPTION_NORMAL : DM_DRAW_OPTION_SKIP;
}
/* draws unselected */
static DMDrawOption draw_mesh_face_select__drawFaceOptsInv(void *userData, int index)
{
Mesh *me = (Mesh *)userData;
MPoly *mpoly = &me->mpoly[index];
if (!(mpoly->flag & ME_HIDE) && !(mpoly->flag & ME_FACE_SEL))
return DM_DRAW_OPTION_NORMAL;
else
return DM_DRAW_OPTION_SKIP;
}
void draw_mesh_face_select(RegionView3D *rv3d, Mesh *me, DerivedMesh *dm, bool draw_select_edges)
{
drawMeshFaceSelect_userData data;
data.me = me;
data.edge_flags = get_tface_mesh_marked_edge_info(me, draw_select_edges);
glEnable(GL_DEPTH_TEST);
ED_view3d_polygon_offset(rv3d, 1.0);
/* Draw (Hidden) Edges */
setlinestyle(1);
UI_ThemeColor(TH_EDGE_FACESEL);
dm->drawMappedEdges(dm, draw_mesh_face_select__setHiddenOpts, &data);
setlinestyle(0);
/* Draw Selected Faces */
if (me->drawflag & ME_DRAWFACES) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/* dull unselected faces so as not to get in the way of seeing color */
glColor4ub(96, 96, 96, 64);
dm->drawMappedFaces(dm, draw_mesh_face_select__drawFaceOptsInv, NULL, NULL, (void *)me, DM_DRAW_SKIP_HIDDEN);
glDisable(GL_BLEND);
}
ED_view3d_polygon_offset(rv3d, 1.0);
/* Draw Stippled Outline for selected faces */
glColor3ub(255, 255, 255);
setlinestyle(1);
dm->drawMappedEdges(dm, draw_mesh_face_select__setSelectOpts, &data);
setlinestyle(0);
ED_view3d_polygon_offset(rv3d, 0.0); /* resets correctly now, even after calling accumulated offsets */
MEM_freeN(data.edge_flags);
}
/***************************** Texture Drawing ******************************/
static Material *give_current_material_or_def(Object *ob, int matnr)
{
extern Material defmaterial; /* render module abuse... */
Material *ma = give_current_material(ob, matnr);
return ma ? ma : &defmaterial;
}
/* Icky globals, fix with userdata parameter */
static struct TextureDrawState {
Object *ob;
Image *stencil; /* texture painting stencil */
Image *canvas; /* texture painting canvas, for image mode */
bool use_game_mat;
int is_lit, is_tex;
int color_profile;
bool use_backface_culling;
bool two_sided_lighting;
unsigned char obcol[4];
bool is_texpaint;
bool texpaint_material; /* use material slots for texture painting */
} Gtexdraw = {NULL, NULL, NULL, false, 0, 0, 0, false, false, {0, 0, 0, 0}, false, false};
static bool set_draw_settings_cached(
int clearcache, MTexPoly *texface, Material *ma,
const struct TextureDrawState *gtexdraw)
{
static Material *c_ma;
static int c_textured;
static MTexPoly c_texface;
static int c_backculled;
static bool c_badtex;
static int c_lit;
static int c_has_texface;
int backculled = 1;
int alphablend = GPU_BLEND_SOLID;
int textured = 0;
int lit = 0;
int has_texface = texface != NULL;
bool need_set_tpage = false;
bool texpaint = ((gtexdraw->ob->mode & OB_MODE_TEXTURE_PAINT) != 0);
Image *ima = NULL;
if (ma != NULL) {
if (ma->mode & MA_TRANSP) {
alphablend = GPU_BLEND_ALPHA;
}
}
if (clearcache) {
c_textured = c_lit = c_backculled = -1;
memset(&c_texface, 0, sizeof(c_texface));
c_badtex = false;
c_has_texface = -1;
c_ma = NULL;
}
else {
textured = gtexdraw->is_tex;
}
/* convert number of lights into boolean */
if (gtexdraw->is_lit) {
lit = 1;
}
backculled = gtexdraw->use_backface_culling;
if (ma) {
if (ma->mode & MA_SHLESS) lit = 0;
if (gtexdraw->use_game_mat) {
backculled = backculled || (ma->game.flag & GEMAT_BACKCULL);
alphablend = ma->game.alpha_blend;
}
}
if (texface && !texpaint) {
textured = textured && (texface->tpage);
/* no material, render alpha if texture has depth=32 */
if (!ma && BKE_image_has_alpha(texface->tpage))
alphablend = GPU_BLEND_ALPHA;
}
else if (texpaint) {
if (gtexdraw->texpaint_material)
ima = ma && ma->texpaintslot ? ma->texpaintslot[ma->paint_active_slot].ima : NULL;
else
ima = gtexdraw->canvas;
}
else
textured = 0;
if (backculled != c_backculled) {
if (backculled) glEnable(GL_CULL_FACE);
else glDisable(GL_CULL_FACE);
c_backculled = backculled;
}
/* need to re-set tpage if textured flag changed or existsment of texface changed.. */
need_set_tpage = textured != c_textured || has_texface != c_has_texface;
/* ..or if settings inside texface were changed (if texface was used) */
need_set_tpage |= (texpaint && c_ma != ma) || (texface && memcmp(&c_texface, texface, sizeof(c_texface)));
if (need_set_tpage) {
if (textured) {
if (texpaint) {
c_badtex = false;
if (GPU_verify_image(ima, NULL, GL_TEXTURE_2D, 0, 1, 0, false)) {
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE);
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
glActiveTexture(GL_TEXTURE0);
}
else {
glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glActiveTexture(GL_TEXTURE0);
c_badtex = true;
GPU_clear_tpage(true);
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}
}
else {
c_badtex = !GPU_set_tpage(texface, !texpaint, alphablend);
}
}
else {
GPU_set_tpage(NULL, 0, 0);
c_badtex = false;
}
c_textured = textured;
c_has_texface = has_texface;
if (texface)
memcpy(&c_texface, texface, sizeof(c_texface));
}
if (c_badtex) lit = 0;
if (lit != c_lit || ma != c_ma || textured != c_textured) {
int options = GPU_SHADER_USE_COLOR;
if (c_textured && !c_badtex) {
options |= GPU_SHADER_TEXTURE_2D;
}
if (gtexdraw->two_sided_lighting) {
options |= GPU_SHADER_TWO_SIDED;
}
if (lit) {
options |= GPU_SHADER_LIGHTING;
if (!ma)
ma = give_current_material_or_def(NULL, 0); /* default material */
float specular[3];
mul_v3_v3fl(specular, &ma->specr, ma->spec);
GPU_basic_shader_colors(NULL, specular, ma->har, 1.0f);
}
GPU_basic_shader_bind(options);
c_lit = lit;
c_ma = ma;
}
return c_badtex;
}
static void draw_textured_begin(Scene *scene, View3D *v3d, RegionView3D *rv3d, Object *ob)
{
unsigned char obcol[4];
bool is_tex, solidtex;
Mesh *me = ob->data;
ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
/* XXX scene->obedit warning */
/* texture draw is abused for mask selection mode, do this so wire draw
* with face selection in weight paint is not lit. */
if ((v3d->drawtype <= OB_WIRE) && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT))) {
solidtex = false;
Gtexdraw.is_lit = 0;
}
else if ((ob->mode & OB_MODE_TEXTURE_PAINT) && BKE_scene_use_new_shading_nodes(scene)) {
solidtex = true;
if (v3d->flag2 & V3D_SHADELESS_TEX)
Gtexdraw.is_lit = 0;
else
Gtexdraw.is_lit = -1;
}
else if ((v3d->drawtype == OB_SOLID) ||
((ob->mode & OB_MODE_EDIT) && (v3d->drawtype != OB_TEXTURE)))
{
/* draw with default lights in solid draw mode and edit mode */
solidtex = true;
Gtexdraw.is_lit = -1;
}
else {
/* draw with lights in the scene otherwise */
solidtex = false;
if (v3d->flag2 & V3D_SHADELESS_TEX) {
Gtexdraw.is_lit = 0;
}
else {
Gtexdraw.is_lit = GPU_scene_object_lights(
scene, ob, v3d->localvd ? v3d->localvd->lay : v3d->lay,
rv3d->viewmat, !rv3d->is_persp);
}
}
rgba_float_to_uchar(obcol, ob->col);
if (solidtex || v3d->drawtype == OB_TEXTURE) is_tex = true;
else is_tex = false;
Gtexdraw.ob = ob;
Gtexdraw.stencil = (imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL) ? imapaint->stencil : NULL;
Gtexdraw.is_texpaint = (ob->mode == OB_MODE_TEXTURE_PAINT);
Gtexdraw.texpaint_material = (imapaint->mode == IMAGEPAINT_MODE_MATERIAL);
Gtexdraw.canvas = (Gtexdraw.texpaint_material) ? NULL : imapaint->canvas;
Gtexdraw.is_tex = is_tex;
/* naughty multitexturing hacks to quickly support stencil + shading + alpha blending
* in new texpaint code. The better solution here would be to support GLSL */
if (Gtexdraw.is_texpaint) {
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
/* load the stencil texture here */
if (Gtexdraw.stencil != NULL) {
glActiveTexture(GL_TEXTURE2);
if (GPU_verify_image(Gtexdraw.stencil, NULL, GL_TEXTURE_2D, false, false, false, false)) {
float col[4] = {imapaint->stencil_col[0], imapaint->stencil_col[1], imapaint->stencil_col[2], 1.0f};
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_CONSTANT);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, col);
if ((imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL_INV) == 0) {
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_ONE_MINUS_SRC_COLOR);
}
else {
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
}
}
}
glActiveTexture(GL_TEXTURE0);
}
Gtexdraw.color_profile = BKE_scene_check_color_management_enabled(scene);
Gtexdraw.use_game_mat = (RE_engines_find(scene->r.engine)->flag & RE_GAME) != 0;
Gtexdraw.use_backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
Gtexdraw.two_sided_lighting = (me->flag & ME_TWOSIDED);
memcpy(Gtexdraw.obcol, obcol, sizeof(obcol));
set_draw_settings_cached(1, NULL, NULL, &Gtexdraw);
glCullFace(GL_BACK);
}
static void draw_textured_end(void)
{
if (Gtexdraw.ob->mode & OB_MODE_TEXTURE_PAINT) {
glActiveTexture(GL_TEXTURE1);
glDisable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, 0);
if (Gtexdraw.stencil != NULL) {
glActiveTexture(GL_TEXTURE2);
glDisable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
/* manual reset, since we don't use tpage */
glBindTexture(GL_TEXTURE_2D, 0);
/* force switch off textures */
GPU_clear_tpage(true);
}
else {
/* switch off textures */
GPU_set_tpage(NULL, 0, 0);
}
glDisable(GL_CULL_FACE);
GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
/* XXX, bad patch - GPU_default_lights() calls
* glLightfv(GL_POSITION, ...) which
* is transformed by the current matrix... we
* need to make sure that matrix is identity.
*
* It would be better if drawmesh.c kept track
* of and restored the light settings it changed.
* - zr
*/
glPushMatrix();
glLoadIdentity();
GPU_default_lights();
glPopMatrix();
}
static DMDrawOption draw_tface__set_draw_legacy(MTexPoly *mtexpoly, const bool has_mcol, int matnr)
{
Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
bool invalidtexture = false;
if (ma && (ma->game.flag & GEMAT_INVISIBLE))
return DM_DRAW_OPTION_SKIP;
invalidtexture = set_draw_settings_cached(0, mtexpoly, ma, &Gtexdraw);
if (mtexpoly && invalidtexture) {
glColor3ub(0xFF, 0x00, 0xFF);
return DM_DRAW_OPTION_NO_MCOL; /* Don't set color */
}
else if (!has_mcol) {
if (mtexpoly) {
glColor3f(1.0, 1.0, 1.0);
}
else {
if (ma) {
if (ma->shade_flag & MA_OBCOLOR) {
glColor3ubv(Gtexdraw.obcol);
}
else {
float col[3];
if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
else copy_v3_v3(col, &ma->r);
glColor3fv(col);
}
}
else {
glColor3f(1.0, 1.0, 1.0);
}
}
return DM_DRAW_OPTION_NORMAL; /* normal drawing (no mcols anyway, no need to turn off) */
}
else {
return DM_DRAW_OPTION_NORMAL; /* Set color from mcol */
}
}
static DMDrawOption draw_tface__set_draw(MTexPoly *mtexpoly, const bool UNUSED(has_mcol), int matnr)
{
Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
if (ma && (ma->game.flag & GEMAT_INVISIBLE)) return DM_DRAW_OPTION_SKIP;
if (mtexpoly || Gtexdraw.is_texpaint)
set_draw_settings_cached(0, mtexpoly, ma, &Gtexdraw);
/* always use color from mcol, as set in update_tface_color_layer */
return DM_DRAW_OPTION_NORMAL;
}
static void update_tface_color_layer(DerivedMesh *dm, bool use_mcol)
{
const MPoly *mp = dm->getPolyArray(dm);
const int mpoly_num = dm->getNumPolys(dm);
MTexPoly *mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
MLoopCol *finalCol;
int i, j;
MLoopCol *mloopcol = NULL;
/* cache material values to avoid a lot of lookups */
Material *ma = NULL;
short mat_nr_prev = -1;
enum {
COPY_CALC,
COPY_ORIG,
COPY_PREV,
} copy_mode = COPY_CALC;
if (use_mcol) {
mloopcol = dm->getLoopDataArray(dm, CD_PREVIEW_MLOOPCOL);
if (!mloopcol)
mloopcol = dm->getLoopDataArray(dm, CD_MLOOPCOL);
}
if (CustomData_has_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL)) {
finalCol = CustomData_get_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL);
}
else {
finalCol = MEM_mallocN(sizeof(MLoopCol) * dm->numLoopData, "add_tface_color_layer");
CustomData_add_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL, CD_ASSIGN, finalCol, dm->numLoopData);
}
for (i = mpoly_num; i--; mp++) {
const short mat_nr = mp->mat_nr;
if (UNLIKELY(mat_nr_prev != mat_nr)) {
ma = give_current_material(Gtexdraw.ob, mat_nr + 1);
copy_mode = COPY_CALC;
mat_nr_prev = mat_nr;
}
/* avoid lookups */
if (copy_mode == COPY_ORIG) {
memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
}
else if (copy_mode == COPY_PREV) {
int loop_index = mp->loopstart;
const MLoopCol *lcol_prev = &finalCol[(mp - 1)->loopstart];
for (j = 0; j < mp->totloop; j++, loop_index++) {
finalCol[loop_index] = *lcol_prev;
}
}
/* (copy_mode == COPY_CALC) */
else if (ma && (ma->game.flag & GEMAT_INVISIBLE)) {
if (mloopcol) {
memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
copy_mode = COPY_ORIG;
}
else {
memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
copy_mode = COPY_PREV;
}
}
else if (mtexpoly && set_draw_settings_cached(0, mtexpoly, ma, &Gtexdraw)) {
int loop_index = mp->loopstart;
for (j = 0; j < mp->totloop; j++, loop_index++) {
finalCol[loop_index].r = 255;
finalCol[loop_index].g = 0;
finalCol[loop_index].b = 255;
}
copy_mode = COPY_PREV;
}
else if (ma && (ma->shade_flag & MA_OBCOLOR)) {
int loop_index = mp->loopstart;
for (j = 0; j < mp->totloop; j++, loop_index++) {
copy_v3_v3_uchar(&finalCol[loop_index].r, Gtexdraw.obcol);
}
copy_mode = COPY_PREV;
}
else {
if (mloopcol) {
memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
copy_mode = COPY_ORIG;
}
else if (mtexpoly) {
memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
copy_mode = COPY_PREV;
}
else {
float col[3];
if (ma) {
int loop_index = mp->loopstart;
MLoopCol lcol;
if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
else copy_v3_v3(col, &ma->r);
rgb_float_to_uchar((unsigned char *)&lcol.r, col);
lcol.a = 255;
for (j = 0; j < mp->totloop; j++, loop_index++) {
finalCol[loop_index] = lcol;
}
}
else {
memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
}
copy_mode = COPY_PREV;
}
}
}
dm->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
}
static DMDrawOption draw_tface_mapped__set_draw(void *userData, int origindex, int UNUSED(mat_nr))
{
const Mesh *me = ((drawTFace_userData *)userData)->me;
/* array checked for NULL before calling */
MPoly *mpoly = &me->mpoly[origindex];
BLI_assert(origindex >= 0 && origindex < me->totpoly);
if (mpoly->flag & ME_HIDE) {
return DM_DRAW_OPTION_SKIP;
}
else {
MTexPoly *tpoly = (me->mtpoly) ? &me->mtpoly[origindex] : NULL;
int matnr = mpoly->mat_nr;
return draw_tface__set_draw(tpoly, (me->mloopcol != NULL), matnr);
}
}
static DMDrawOption draw_em_tf_mapped__set_draw(void *userData, int origindex, int mat_nr)
{
drawEMTFMapped_userData *data = userData;
BMEditMesh *em = data->em;
BMFace *efa;
if (UNLIKELY(origindex >= em->bm->totface))
return DM_DRAW_OPTION_NORMAL;
efa = BM_face_at_index(em->bm, origindex);
if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
return DM_DRAW_OPTION_SKIP;
}
else {
MTexPoly *mtexpoly = (data->cd_poly_tex_offset != -1) ?
BM_ELEM_CD_GET_VOID_P(efa, data->cd_poly_tex_offset) : NULL;
int matnr = (mat_nr != -1) ? mat_nr : efa->mat_nr;
return draw_tface__set_draw_legacy(mtexpoly, data->has_mcol, matnr);
}
}
/* when face select is on, use face hidden flag */
static DMDrawOption wpaint__setSolidDrawOptions_facemask(void *userData, int index)
{
Mesh *me = (Mesh *)userData;
MPoly *mp = &me->mpoly[index];
if (mp->flag & ME_HIDE)
return DM_DRAW_OPTION_SKIP;
return DM_DRAW_OPTION_NORMAL;
}
static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
{
Mesh *me = ob->data;
DerivedMesh *ddm;
MPoly *mp, *mface = me->mpoly;
MTexPoly *mtpoly = me->mtpoly;
MLoopUV *mloopuv = me->mloopuv;
MLoopUV *luv;
MLoopCol *mloopcol = me->mloopcol; /* why does mcol exist? */
MLoopCol *lcol;
bProperty *prop = BKE_bproperty_object_get(ob, "Text");
GPUVertexAttribs gattribs;
int a, totpoly = me->totpoly;
/* fake values to pass to GPU_render_text() */
MCol tmp_mcol[4] = {{0}};
MCol *tmp_mcol_pt = mloopcol ? tmp_mcol : NULL;
/* don't draw without tfaces */
if (!mtpoly || !mloopuv)
return;
/* don't draw when editing */
if (ob->mode & OB_MODE_EDIT)
return;
else if (ob == OBACT)
if (BKE_paint_select_elem_test(ob))
return;
ddm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
for (a = 0, mp = mface; a < totpoly; a++, mtpoly++, mp++) {
short matnr = mp->mat_nr;
const bool mf_smooth = (mp->flag & ME_SMOOTH) != 0;
Material *mat = (me->mat) ? me->mat[matnr] : NULL;
int mode = mat ? mat->game.flag : GEMAT_INVISIBLE;
if (!(mode & GEMAT_INVISIBLE) && (mode & GEMAT_TEXT) && mp->totloop >= 3) {
/* get the polygon as a tri/quad */
int mp_vi[4];
float v_quad_data[4][3];
const float *v_quad[4];
const float *uv_quad[4];
char string[MAX_PROPSTRING];
int characters, i, glattrib = -1, badtex = 0;
/* TEXFACE */
if (glsl) {
GPU_object_material_bind(matnr + 1, &gattribs);
for (i = 0; i < gattribs.totlayer; i++) {
if (gattribs.layer[i].type == CD_MTFACE) {
glattrib = gattribs.layer[i].glindex;
break;
}
}
}
else {
badtex = set_draw_settings_cached(0, mtpoly, mat, &Gtexdraw);
if (badtex) {
continue;
}
}
mp_vi[0] = me->mloop[mp->loopstart + 0].v;
mp_vi[1] = me->mloop[mp->loopstart + 1].v;
mp_vi[2] = me->mloop[mp->loopstart + 2].v;
mp_vi[3] = (mp->totloop >= 4) ? me->mloop[mp->loopstart + 3].v : 0;
/* UV */
luv = &mloopuv[mp->loopstart];
uv_quad[0] = luv->uv; luv++;
uv_quad[1] = luv->uv; luv++;
uv_quad[2] = luv->uv; luv++;
if (mp->totloop >= 4) {
uv_quad[3] = luv->uv;
}
else {
uv_quad[3] = NULL;
}
/* COLOR */
if (mloopcol) {
unsigned int totloop_clamp = min_ii(4, mp->totloop);
unsigned int j;
lcol = &mloopcol[mp->loopstart];
for (j = 0; j < totloop_clamp; j++, lcol++) {
MESH_MLOOPCOL_TO_MCOL(lcol, &tmp_mcol[j]);
}
}
/* LOCATION */
ddm->getVertCo(ddm, mp_vi[0], v_quad_data[0]);
ddm->getVertCo(ddm, mp_vi[1], v_quad_data[1]);
ddm->getVertCo(ddm, mp_vi[2], v_quad_data[2]);
if (mp->totloop >= 4) {
ddm->getVertCo(ddm, mp_vi[3], v_quad_data[3]);
}
v_quad[0] = v_quad_data[0];
v_quad[1] = v_quad_data[1];
v_quad[2] = v_quad_data[2];
if (mp->totloop >= 4) {
v_quad[3] = v_quad_data[2];
}
else {
v_quad[3] = NULL;
}
/* The BM_FONT handling is in the gpu module, shared with the
* game engine, was duplicated previously */
BKE_bproperty_set_valstr(prop, string);
characters = strlen(string);
if (!BKE_image_has_ibuf(mtpoly->tpage, NULL))
characters = 0;
if (!mf_smooth) {
float nor[3];
normal_tri_v3(nor, v_quad[0], v_quad[1], v_quad[2]);
glNormal3fv(nor);
}
GPU_render_text(
mtpoly, mode, string, characters,
(unsigned int *)tmp_mcol_pt,
v_quad, uv_quad,
glattrib);
}
}
ddm->release(ddm);
}
static int compareDrawOptions(void *userData, int cur_index, int next_index)
{
drawTFace_userData *data = userData;
if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
return 0;
if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
return 0;
return 1;
}
static int compareDrawOptionsEm(void *userData, int cur_index, int next_index)
{
drawEMTFMapped_userData *data = userData;
if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
return 0;
if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
return 0;
return 1;
}
static void draw_mesh_textured_old(Scene *scene, View3D *v3d, RegionView3D *rv3d,
Object *ob, DerivedMesh *dm, const int draw_flags)
{
Mesh *me = ob->data;
/* correct for negative scale */
if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
else glFrontFace(GL_CCW);
/* draw the textured mesh */
draw_textured_begin(scene, v3d, rv3d, ob);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
if (ob->mode & OB_MODE_EDIT) {
drawEMTFMapped_userData data;
data.em = me->edit_btmesh;
data.has_mcol = CustomData_has_layer(&me->edit_btmesh->bm->ldata, CD_MLOOPCOL);
data.cd_poly_tex_offset = CustomData_get_offset(&me->edit_btmesh->bm->pdata, CD_MTEXPOLY);
data.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
data.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
dm->drawMappedFacesTex(dm, draw_em_tf_mapped__set_draw, compareDrawOptionsEm, &data, 0);
}
else {
DMDrawFlag dm_draw_flag;
drawTFace_userData userData;
if (ob->mode & OB_MODE_TEXTURE_PAINT) {
dm_draw_flag = DM_DRAW_USE_TEXPAINT_UV;
}
else {
dm_draw_flag = DM_DRAW_USE_ACTIVE_UV;
}
if (ob == OBACT) {
if (ob->mode & OB_MODE_WEIGHT_PAINT) {
dm_draw_flag |= DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH | DM_DRAW_SKIP_HIDDEN;
}
else if (ob->mode & OB_MODE_SCULPT) {
dm_draw_flag |= DM_DRAW_SKIP_HIDDEN | DM_DRAW_USE_COLORS;
}
else if ((ob->mode & OB_MODE_TEXTURE_PAINT) == 0) {
dm_draw_flag |= DM_DRAW_USE_COLORS;
}
}
else {
if ((ob->mode & OB_MODE_TEXTURE_PAINT) == 0) {
dm_draw_flag |= DM_DRAW_USE_COLORS;
}
}
userData.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
userData.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
if (draw_flags & DRAW_FACE_SELECT) {
userData.me = me;
dm->drawMappedFacesTex(
dm, me->mpoly ? draw_tface_mapped__set_draw : NULL, compareDrawOptions,
&userData, dm_draw_flag);
}
else {
userData.me = NULL;
/* if ((ob->mode & OB_MODE_ALL_PAINT) == 0) */ {
/* Note: this isn't efficient and runs on every redraw,
* its needed so material colors are used for vertex colors.
* In the future we will likely remove 'texface' so, just avoid running this where possible,
* (when vertex paint or weight paint are used).
*
* Note 2: We disable optimization for now since it causes T48788
* and it is now too close to release to do something smarter.
*
* TODO(sergey): Find some real solution here.
*/
update_tface_color_layer(dm, !(ob->mode & OB_MODE_TEXTURE_PAINT));
}
dm->drawFacesTex(
dm, draw_tface__set_draw, compareDrawOptions,
&userData, dm_draw_flag);
}
}
/* draw game engine text hack */
if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
if (BKE_bproperty_object_get(ob, "Text")) {
draw_mesh_text(scene, ob, 0);
}
}
draw_textured_end();
/* draw edges and selected faces over textured mesh */
if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
}
/* reset from negative scale correction */
glFrontFace(GL_CCW);
/* in editmode, the blend mode needs to be set in case it was ADD */
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
/************************** NEW SHADING NODES ********************************/
typedef struct TexMatCallback {
Scene *scene;
Object *ob;
Mesh *me;
DerivedMesh *dm;
bool shadeless;
bool two_sided_lighting;
} TexMatCallback;
static void tex_mat_set_material_cb(void *UNUSED(userData), int mat_nr, void *attribs)
{
/* all we have to do here is simply enable the GLSL material, but note
* that the GLSL code will give different result depending on the drawtype,
* in texture draw mode it will output the active texture node, in material
* draw mode it will show the full material. */
GPU_object_material_bind(mat_nr, attribs);
}
static void tex_mat_set_texture_cb(void *userData, int mat_nr, void *attribs)
{
/* texture draw mode without GLSL */
TexMatCallback *data = (TexMatCallback *)userData;
GPUVertexAttribs *gattribs = attribs;
Image *ima;
ImageUser *iuser;
bNode *node;
/* draw image texture if we find one */
if (ED_object_get_active_image(data->ob, mat_nr, &ima, &iuser, &node, NULL)) {
/* get openl texture */
int mipmap = 1;
int bindcode = (ima) ? GPU_verify_image(ima, iuser, GL_TEXTURE_2D, 0, 0, mipmap, false) : 0;
if (bindcode) {
NodeTexBase *texbase = node->storage;
/* disable existing material */
GPU_object_material_unbind();
/* bind texture */
glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
glMatrixMode(GL_TEXTURE);
glLoadMatrixf(texbase->tex_mapping.mat);
glMatrixMode(GL_MODELVIEW);
/* use active UV texture layer */
memset(gattribs, 0, sizeof(*gattribs));
gattribs->layer[0].type = CD_MTFACE;
gattribs->layer[0].name[0] = '\0';
gattribs->layer[0].gltexco = 1;
gattribs->totlayer = 1;
/* bind material */
float diffuse[3] = {1.0f, 1.0f, 1.0f};
int options = GPU_SHADER_TEXTURE_2D;
if (!data->shadeless)
options |= GPU_SHADER_LIGHTING;
if (data->two_sided_lighting)
options |= GPU_SHADER_TWO_SIDED;
GPU_basic_shader_colors(diffuse, NULL, 0, 1.0f);
GPU_basic_shader_bind(options);
return;
}
}
/* disable texture material */
GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
if (data->shadeless) {
glColor3f(1.0f, 1.0f, 1.0f);
memset(gattribs, 0, sizeof(*gattribs));
}
else {
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
/* enable solid material */
GPU_object_material_bind(mat_nr, attribs);
}
}
static bool tex_mat_set_face_mesh_cb(void *userData, int index)
{
/* faceselect mode face hiding */
TexMatCallback *data = (TexMatCallback *)userData;
Mesh *me = (Mesh *)data->me;
MPoly *mp = &me->mpoly[index];
return !(mp->flag & ME_HIDE);
}
static bool tex_mat_set_face_editmesh_cb(void *userData, int index)
{
/* editmode face hiding */
TexMatCallback *data = (TexMatCallback *)userData;
Mesh *me = (Mesh *)data->me;
BMEditMesh *em = me->edit_btmesh;
BMFace *efa;
if (UNLIKELY(index >= em->bm->totface))
return DM_DRAW_OPTION_NORMAL;
efa = BM_face_at_index(em->bm, index);
return !BM_elem_flag_test(efa, BM_ELEM_HIDDEN);
}
void draw_mesh_textured(Scene *scene, View3D *v3d, RegionView3D *rv3d,
Object *ob, DerivedMesh *dm, const int draw_flags)
{
/* if not cycles, or preview-modifiers, or drawing matcaps */
if ((draw_flags & DRAW_MODIFIERS_PREVIEW) ||
(v3d->flag2 & V3D_SHOW_SOLID_MATCAP) ||
(BKE_scene_use_new_shading_nodes(scene) == false) ||
((ob->mode & OB_MODE_TEXTURE_PAINT) && ELEM(v3d->drawtype, OB_TEXTURE, OB_SOLID)))
{
draw_mesh_textured_old(scene, v3d, rv3d, ob, dm, draw_flags);
return;
}
else if (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
draw_mesh_paint(v3d, rv3d, ob, dm, draw_flags);
return;
}
/* set opengl state for negative scale & color */
if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
else glFrontFace(GL_CCW);
Mesh *me = ob->data;
bool shadeless = ((v3d->flag2 & V3D_SHADELESS_TEX) &&
((v3d->drawtype == OB_TEXTURE) || (ob->mode & OB_MODE_TEXTURE_PAINT)));
bool two_sided_lighting = (me->flag & ME_TWOSIDED) != 0;
TexMatCallback data = {scene, ob, me, dm, shadeless, two_sided_lighting};
bool (*set_face_cb)(void *, int);
bool picking = (G.f & G_PICKSEL) != 0;
/* face hiding callback depending on mode */
if (ob == scene->obedit)
set_face_cb = tex_mat_set_face_editmesh_cb;
else if (draw_flags & DRAW_FACE_SELECT)
set_face_cb = tex_mat_set_face_mesh_cb;
else
set_face_cb = NULL;
/* test if we can use glsl */
const int drawtype = view3d_effective_drawtype(v3d);
bool glsl = (drawtype == OB_MATERIAL) && !picking;
GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl, NULL);
if (glsl || picking) {
/* draw glsl or solid */
dm->drawMappedFacesMat(dm,
tex_mat_set_material_cb,
set_face_cb, &data);
}
else {
/* draw textured */
dm->drawMappedFacesMat(dm,
tex_mat_set_texture_cb,
set_face_cb, &data);
}
GPU_end_object_materials();
/* reset opengl state */
GPU_end_object_materials();
GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
glBindTexture(GL_TEXTURE_2D, 0);
glFrontFace(GL_CCW);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
/* faceselect mode drawing over textured mesh */
if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
draw_mesh_face_select(rv3d, ob->data, dm, draw_select_edges);
}
}
/* Vertex Paint and Weight Paint */
static void draw_mesh_paint_light_begin(void)
{
/* get material diffuse color from vertex colors but set default spec */
const float specular[3] = {0.47f, 0.47f, 0.47f};
GPU_basic_shader_colors(NULL, specular, 35, 1.0f);
GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_USE_COLOR);
}
static void draw_mesh_paint_light_end(void)
{
GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
}
void draw_mesh_paint_weight_faces(DerivedMesh *dm, const bool use_light,
void *facemask_cb, void *user_data)
{
DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
int flags = DM_DRAW_USE_COLORS;
if (use_light) {
draw_mesh_paint_light_begin();
flags |= DM_DRAW_NEED_NORMALS;
}
dm->drawMappedFaces(dm, (DMSetDrawOptions)facemask_cb, setMaterial, NULL, user_data, flags);
if (use_light) {
draw_mesh_paint_light_end();
}
}
void draw_mesh_paint_vcolor_faces(DerivedMesh *dm, const bool use_light,
void *facemask_cb, void *user_data,
const Mesh *me)
{
DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
int flags = 0;
if (use_light) {
draw_mesh_paint_light_begin();
flags |= DM_DRAW_NEED_NORMALS;
}
if (me->mloopcol) {
dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data,
DM_DRAW_USE_COLORS | flags);
}
else {
glColor3f(1.0f, 1.0f, 1.0f);
dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data, flags);
}
if (use_light) {
draw_mesh_paint_light_end();
}
}
void draw_mesh_paint_weight_edges(RegionView3D *rv3d, DerivedMesh *dm,
const bool use_depth, const bool use_alpha,
void *edgemask_cb, void *user_data)
{
/* weight paint in solid mode, special case. focus on making the weights clear
* rather than the shading, this is also forced in wire view */
if (use_depth) {
ED_view3d_polygon_offset(rv3d, 1.0);
glDepthMask(0); /* disable write in zbuffer, selected edge wires show better */
}
else {
glDisable(GL_DEPTH_TEST);
}
if (use_alpha) {
glEnable(GL_BLEND);
}
glColor4ub(255, 255, 255, 96);
GPU_basic_shader_bind_enable(GPU_SHADER_LINE | GPU_SHADER_STIPPLE);
GPU_basic_shader_line_stipple(1, 0xAAAA);
dm->drawMappedEdges(dm, (DMSetDrawOptions)edgemask_cb, user_data);
if (use_depth) {
ED_view3d_polygon_offset(rv3d, 0.0);
glDepthMask(1);
}
else {
glEnable(GL_DEPTH_TEST);
}
GPU_basic_shader_bind_disable(GPU_SHADER_LINE | GPU_SHADER_STIPPLE);
if (use_alpha) {
glDisable(GL_BLEND);
}
}
void draw_mesh_paint(View3D *v3d, RegionView3D *rv3d,
Object *ob, DerivedMesh *dm, const int draw_flags)
{
DMSetDrawOptions facemask = NULL;
Mesh *me = ob->data;
const bool use_light = (v3d->drawtype >= OB_SOLID);
/* hide faces in face select mode */
if (me->editflag & (ME_EDIT_PAINT_VERT_SEL | ME_EDIT_PAINT_FACE_SEL))
facemask = wpaint__setSolidDrawOptions_facemask;
if (ob->mode & OB_MODE_WEIGHT_PAINT) {
draw_mesh_paint_weight_faces(dm, use_light, facemask, me);
}
else if (ob->mode & OB_MODE_VERTEX_PAINT) {
draw_mesh_paint_vcolor_faces(dm, use_light, facemask, me, me);
}
/* draw face selection on top */
if (draw_flags & DRAW_FACE_SELECT) {
bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
}
else if ((use_light == false) || (ob->dtx & OB_DRAWWIRE)) {
const bool use_depth = (v3d->flag & V3D_ZBUF_SELECT) || !(ob->mode & OB_MODE_WEIGHT_PAINT);
const bool use_alpha = (ob->mode & OB_MODE_VERTEX_PAINT) == 0;
if (use_alpha == false) {
set_inverted_drawing(1);
}
draw_mesh_paint_weight_edges(rv3d, dm, use_depth, use_alpha, NULL, NULL);
if (use_alpha == false) {
set_inverted_drawing(0);
}
}
}
| 28.742283 | 113 | 0.690294 | [
"mesh",
"render",
"object",
"solid"
] |
ecc1809b57a1dbf60cabfed2faea411778e47117 | 5,150 | c | C | src/rotate_basis.c | ccao/WannSymm | 3d29170c14076465d7233cdacabcf473f12487d9 | [
"BSD-3-Clause"
] | 15 | 2021-10-20T06:53:03.000Z | 2022-03-17T11:46:41.000Z | src/rotate_basis.c | ccao/WannSymm | 3d29170c14076465d7233cdacabcf473f12487d9 | [
"BSD-3-Clause"
] | 7 | 2021-11-06T17:12:01.000Z | 2022-03-09T14:04:33.000Z | src/rotate_basis.c | ccao/WannSymm | 3d29170c14076465d7233cdacabcf473f12487d9 | [
"BSD-3-Clause"
] | 1 | 2021-12-16T10:13:32.000Z | 2021-12-16T10:13:32.000Z | #include "rotate_basis.h"
void get_sym_op_reciprocalspace(dcomplex * sym_op, double lattice[3][3], wannorb * orb_info, int norb, int isym_in_doublegp, double rotation[3][3],double translation[3], int TR, double rot_kd[3][3], vector kpt, int flag_soc) {
//
// trans from ccao's fortran code
//
// This function defines the rotation in the Hilbert space
// <W'|R|W>
// For each Wannier orbital, we indeed have 4 labels:
// |W> = | Rv, tau, l, m>
// where Rv is the lattice vector
// tau is the atomic position
// l is the angular momentum
// m indexes the actual orbital (mostly cubic harmonics)
// Therefore
// <Rv', tau', l, m' | R | Rv, tau, l, m> is the matrix element
// lm part rotation matrix is exacly what we had for Ylm or cubic harmonics
// <Rv', tau' | R | Rv, tau> is a delta function
// For real-space rotation, above is just fine
// However, here we rotate |kv, tau, l, m> = \sum(Rv) exp(-i (kv*Rv)) | Rv, tau, l, m>
// under rotation, kv -> kv', Rv+tau -> Rv'+tau'
// notice that Rv' and R*Rv can differ by a lattice vector Rv", Rv'=R*Rv+R"
// thus under rotation, exp(-i (kv*Rv))=exp(-i (kv'*R*Rv))=exp(-i (kv'*Rv'))*exp(i(kv'*Rv"))
// Therefore
// \sum(Rv') exp(-i (kv'*Rv')) | Rv', tau', l, m>
// =\sum(Rv") exp(-i (kv'*Rv")) *exp(-i (kv'* R*Rv)) |Rv', tau', l, m>
//
// isym_in_doublegp : index of symm in double group, range [-nsymm, nsymm-1], nsymm is num of symm in single-valued group
// if( fabs(translation[0]) > 1E-3 || fabs(translation[1]) > 1E-3 || fabs(translation[2]) > 1E-3){
// fprintf(stderr, "Warning, non symmorphic symmetry detected\n");
// }
int i,j,k;
int ii,jj,kk;
int io,jo;
dcomplex * orb_rot[MAX_L+1];
dcomplex * s_rot;
double rot_axis[3];
double rot_angle;
int inv_flag;
double inv_rot[3][3];
vector kpt_roted;
vector rvec_supp; // tau' = rot*tau - rvec_supp
vector tau1,tau2,tau2_roted, tau2_symed;
vector translation_v;
vector inv_trans;
//vector translation_kd_v;
int l, N;
int mr1,mr2;
int ms1,ms2;
init_vector(&translation_v, translation[0], translation[1], translation[2]);
//init_vector(&translation_kd_v, translation_kd[0], translation_kd[1], translation_kd[2]);
matrix3x3_inverse(inv_rot, rotation);
inv_trans = vector_rotate(translation_v, inv_rot);
inv_trans.x *= -1;
inv_trans.y *= -1;
inv_trans.z *= -1;
get_axis_angle_of_rotation(rot_axis, &rot_angle, &inv_flag, rotation, lattice);
if(flag_soc == 1) {
if(isym_in_doublegp < 0) {
rot_angle += 2*PI; // element introduced by double group
}
}
//rot_angle *= -1; // proper rotation or inverse rotation
//get s_rot with input (axis,angle,inv)
s_rot = (dcomplex *)malloc(sizeof(dcomplex)*2*2);
rotate_spinor(s_rot, rot_axis, rot_angle, inv_flag);
if(flag_soc == 0){
s_rot[0] = s_rot[3] = 1;
s_rot[1] = s_rot[2] = 0;
}
//get orb_rot with input (l,axis,angle,inv)
for (l=0;l<=3;l++){
N = 2*l + 1;
orb_rot[l] = (dcomplex *)malloc(sizeof(dcomplex)*N*N);
rotate_cubic( orb_rot[l], l, rot_axis, rot_angle, inv_flag);
}
kpt_roted = vector_rotate(kpt, rot_kd);
if(TR==1){
kpt_roted = vector_scale(-1.0, kpt_roted);
}
for(io=0;io<norb;io++){
for(jo=0;jo<norb;jo++){
//if( ! kpt_equivalent(kpt_roted, kpt) ){
// sym_op[io*norb+jo] = 0;
// continue;
//}
if( (orb_info+io)->l != (orb_info+jo)->l ){
sym_op[io*norb+jo] = 0;
continue;
}
tau1 = (orb_info+io)->site;
tau2 = (orb_info+jo)->site;
tau2_roted = vector_rotate(tau2, rotation);
tau2_roted = vector_add( tau2_roted, translation_v);
//tau2_roted = vector_rotate(tau2, inv_rot);
//tau2_roted = vector_add( tau2_roted, inv_trans);
getrvec_and_site(&rvec_supp, &tau2_symed, tau2_roted, orb_info, norb, lattice);
if( ! equale(tau1, tau2_symed, 1E-5)){
sym_op[io*norb+jo] = 0;
continue;
}
l = (orb_info+jo)->l;
mr1 = (orb_info+io)->mr;
mr2 = (orb_info+jo)->mr;
ms1 = (orb_info+io)->ms;
ms2 = (orb_info+jo)->ms;
//sym_op[io*norb+jo] =cexp(2*PI*cmplx_i * (dot_product(kpt_roted, vector_sub(rvec_supp,translation_v))))*
//sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, rvec_supp)))*
//sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, vector_add(rvec_supp,translation_v))))*
sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, vector_sub(rvec_supp,translation_v))))*
(orb_rot[l][(2*l+1)*(mr1-1) + mr2-1]) *
(s_rot[2*ms1 + ms2]);
sym_op[io*norb+jo] = conj(sym_op[io*norb+jo]);
}
}
}
| 39.312977 | 226 | 0.565243 | [
"vector"
] |
ecc4f9ea7bba2b1a77b62eae21bf4849c9f263a2 | 3,381 | h | C | aws-cpp-sdk-rekognition/include/aws/rekognition/model/FaceMatch.h | woohoou/aws-sdk-cpp | a42835a8aad2eac1e334d899a3fbfedcaa341d51 | [
"Apache-2.0"
] | 1 | 2020-07-16T19:03:13.000Z | 2020-07-16T19:03:13.000Z | aws-cpp-sdk-rekognition/include/aws/rekognition/model/FaceMatch.h | woohoou/aws-sdk-cpp | a42835a8aad2eac1e334d899a3fbfedcaa341d51 | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-rekognition/include/aws/rekognition/model/FaceMatch.h | woohoou/aws-sdk-cpp | a42835a8aad2eac1e334d899a3fbfedcaa341d51 | [
"Apache-2.0"
] | 1 | 2021-10-01T15:29:44.000Z | 2021-10-01T15:29:44.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/rekognition/Rekognition_EXPORTS.h>
#include <aws/rekognition/model/Face.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Rekognition
{
namespace Model
{
/**
* <p>Provides face metadata. In addition, it also provides the confidence in the
* match of this face with the input face.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/rekognition-2016-06-27/FaceMatch">AWS
* API Reference</a></p>
*/
class AWS_REKOGNITION_API FaceMatch
{
public:
FaceMatch();
FaceMatch(const Aws::Utils::Json::JsonValue& jsonValue);
FaceMatch& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Confidence in the match of this face with the input face.</p>
*/
inline double GetSimilarity() const{ return m_similarity; }
/**
* <p>Confidence in the match of this face with the input face.</p>
*/
inline void SetSimilarity(double value) { m_similarityHasBeenSet = true; m_similarity = value; }
/**
* <p>Confidence in the match of this face with the input face.</p>
*/
inline FaceMatch& WithSimilarity(double value) { SetSimilarity(value); return *this;}
/**
* <p>Describes the face properties such as the bounding box, face ID, image ID of
* the source image, and external image ID that you assigned.</p>
*/
inline const Face& GetFace() const{ return m_face; }
/**
* <p>Describes the face properties such as the bounding box, face ID, image ID of
* the source image, and external image ID that you assigned.</p>
*/
inline void SetFace(const Face& value) { m_faceHasBeenSet = true; m_face = value; }
/**
* <p>Describes the face properties such as the bounding box, face ID, image ID of
* the source image, and external image ID that you assigned.</p>
*/
inline void SetFace(Face&& value) { m_faceHasBeenSet = true; m_face = std::move(value); }
/**
* <p>Describes the face properties such as the bounding box, face ID, image ID of
* the source image, and external image ID that you assigned.</p>
*/
inline FaceMatch& WithFace(const Face& value) { SetFace(value); return *this;}
/**
* <p>Describes the face properties such as the bounding box, face ID, image ID of
* the source image, and external image ID that you assigned.</p>
*/
inline FaceMatch& WithFace(Face&& value) { SetFace(std::move(value)); return *this;}
private:
double m_similarity;
bool m_similarityHasBeenSet;
Face m_face;
bool m_faceHasBeenSet;
};
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| 31.305556 | 100 | 0.680864 | [
"model"
] |
ecce27bacb1f4b142b685136bd8b2382a5216345 | 104,236 | h | C | Graphics/GraphicsEngine/interface/GraphicsTypes.h | speedym/DiligentCore | 982f1d6b09d0569f7a83a497eb44f08d0a8c5f4c | [
"Apache-2.0"
] | null | null | null | Graphics/GraphicsEngine/interface/GraphicsTypes.h | speedym/DiligentCore | 982f1d6b09d0569f7a83a497eb44f08d0a8c5f4c | [
"Apache-2.0"
] | null | null | null | Graphics/GraphicsEngine/interface/GraphicsTypes.h | speedym/DiligentCore | 982f1d6b09d0569f7a83a497eb44f08d0a8c5f4c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
// clang-format off
/// \file
/// Contains basic graphics engine type defintions
#include "../../../Primitives/interface/BasicTypes.h"
#include "../../../Primitives/interface/DebugOutput.h"
#include "../../../Primitives/interface/FlagEnum.h"
#include "../../../Platforms/interface/NativeWindow.h"
#include "APIInfo.h"
/// Graphics engine namespace
DILIGENT_BEGIN_NAMESPACE(Diligent)
struct ITexture;
struct IBuffer;
/// Value type
/// This enumeration describes value type. It is used by
/// - BufferDesc structure to describe value type of a formatted buffer
/// - DrawAttribs structure to describe index type for an indexed draw call
DILIGENT_TYPED_ENUM(VALUE_TYPE, Uint8)
{
VT_UNDEFINED = 0, ///< Undefined type
VT_INT8, ///< Signed 8-bit integer
VT_INT16, ///< Signed 16-bit integer
VT_INT32, ///< Signed 32-bit integer
VT_UINT8, ///< Unsigned 8-bit integer
VT_UINT16, ///< Unsigned 16-bit integer
VT_UINT32, ///< Unsigned 32-bit integer
VT_FLOAT16, ///< Half-precision 16-bit floating point
VT_FLOAT32, ///< Full-precision 32-bit floating point
VT_NUM_TYPES ///< Helper value storing total number of types in the enumeration
};
/// Resource binding flags
/// [D3D11_BIND_FLAG]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476085(v=vs.85).aspx
///
/// This enumeration describes which parts of the pipeline a resource can be bound to.
/// It generally mirrors [D3D11_BIND_FLAG][] enumeration. It is used by
/// - BufferDesc to describe bind flags for a buffer
/// - TextureDesc to describe bind flags for a texture
DILIGENT_TYPED_ENUM(BIND_FLAGS, Uint32)
{
BIND_NONE = 0x0L, ///< Undefined binding
BIND_VERTEX_BUFFER = 0x1L, ///< A buffer can be bound as a vertex buffer
BIND_INDEX_BUFFER = 0x2L, ///< A buffer can be bound as an index buffer
BIND_UNIFORM_BUFFER = 0x4L, ///< A buffer can be bound as a uniform buffer
/// \warning This flag may not be combined with any other bind flag
BIND_SHADER_RESOURCE = 0x8L, ///< A buffer or a texture can be bound as a shader resource
/// \warning This flag cannot be used with MAP_WRITE_NO_OVERWRITE flag
BIND_STREAM_OUTPUT = 0x10L,///< A buffer can be bound as a target for stream output stage
BIND_RENDER_TARGET = 0x20L,///< A texture can be bound as a render target
BIND_DEPTH_STENCIL = 0x40L,///< A texture can be bound as a depth-stencil target
BIND_UNORDERED_ACCESS = 0x80L,///< A buffer or a texture can be bound as an unordered access view
BIND_INDIRECT_DRAW_ARGS = 0x100L///< A buffer can be bound as the source buffer for indirect draw commands
};
DEFINE_FLAG_ENUM_OPERATORS(BIND_FLAGS)
/// Resource usage
/// [D3D11_USAGE]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476259(v=vs.85).aspx
/// This enumeration describes expected resource usage. It generally mirrors [D3D11_USAGE] enumeration.
/// The enumeration is used by
/// - BufferDesc to describe usage for a buffer
/// - TextureDesc to describe usage for a texture
DILIGENT_TYPED_ENUM(USAGE, Uint8)
{
/// A resource that can only be read by the GPU. It cannot be written by the GPU,
/// and cannot be accessed at all by the CPU. This type of resource must be initialized
/// when it is created, since it cannot be changed after creation. \n
/// D3D11 Counterpart: D3D11_USAGE_IMMUTABLE. OpenGL counterpart: GL_STATIC_DRAW
USAGE_STATIC = 0,
/// A resource that requires read and write access by the GPU and can also be occasionally
/// written by the CPU. \n
/// D3D11 Counterpart: D3D11_USAGE_DEFAULT. OpenGL counterpart: GL_DYNAMIC_DRAW
USAGE_DEFAULT,
/// A resource that can be read by the GPU and written at least once per frame by the CPU. \n
/// D3D11 Counterpart: D3D11_USAGE_DYNAMIC. OpenGL counterpart: GL_STREAM_DRAW
USAGE_DYNAMIC,
/// A resource that facilitates transferring data from GPU to CPU. \n
/// D3D11 Counterpart: D3D11_USAGE_STAGING. OpenGL counterpart: GL_DYNAMIC_READ
USAGE_STAGING
};
/// Allowed CPU access mode flags when mapping a resource
/// The enumeration is used by
/// - BufferDesc to describe CPU access mode for a buffer
/// - TextureDesc to describe CPU access mode for a texture
/// \note Only USAGE_DYNAMIC resources can be mapped
DILIGENT_TYPED_ENUM(CPU_ACCESS_FLAGS, Uint8)
{
CPU_ACCESS_NONE = 0x00, ///< No CPU access
CPU_ACCESS_READ = 0x01, ///< A resource can be mapped for reading
CPU_ACCESS_WRITE = 0x02 ///< A resource can be mapped for writing
};
DEFINE_FLAG_ENUM_OPERATORS(CPU_ACCESS_FLAGS)
/// Resource mapping type
/// [D3D11_MAP]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476181(v=vs.85).aspx
/// Describes how a mapped resource will be accessed. This enumeration generally
/// mirrors [D3D11_MAP][] enumeration. It is used by
/// - IBuffer::Map to describe buffer mapping type
/// - ITexture::Map to describe texture mapping type
DILIGENT_TYPED_ENUM(MAP_TYPE, Uint8)
{
/// The resource is mapped for reading. \n
/// D3D11 counterpart: D3D11_MAP_READ. OpenGL counterpart: GL_MAP_READ_BIT
MAP_READ = 0x01,
/// The resource is mapped for writing. \n
/// D3D11 counterpart: D3D11_MAP_WRITE. OpenGL counterpart: GL_MAP_WRITE_BIT
MAP_WRITE = 0x02,
/// The resource is mapped for reading and writing. \n
/// D3D11 counterpart: D3D11_MAP_READ_WRITE. OpenGL counterpart: GL_MAP_WRITE_BIT | GL_MAP_READ_BIT
MAP_READ_WRITE = 0x03
};
/// Special map flags
/// Describes special arguments for a map operation.
/// This enumeration is used by
/// - IBuffer::Map to describe buffer mapping flags
/// - ITexture::Map to describe texture mapping flags
DILIGENT_TYPED_ENUM(MAP_FLAGS, Uint8)
{
MAP_FLAG_NONE = 0x000,
/// Specifies that map operation should not wait until previous command that
/// using the same resource completes. Map returns null pointer if the resource
/// is still in use.\n
/// D3D11 counterpart: D3D11_MAP_FLAG_DO_NOT_WAIT
/// \note: OpenGL does not have corresponding flag, so a buffer will always be mapped
MAP_FLAG_DO_NOT_WAIT = 0x001,
/// Previous contents of the resource will be undefined. This flag is only compatible with MAP_WRITE\n
/// D3D11 counterpart: D3D11_MAP_WRITE_DISCARD. OpenGL counterpart: GL_MAP_INVALIDATE_BUFFER_BIT
/// \note OpenGL implementation may orphan a buffer instead
MAP_FLAG_DISCARD = 0x002,
/// The system will not synchronize pending operations before mapping the buffer. It is responsibility
/// of the application to make sure that the buffer contents is not overwritten while it is in use by
/// the GPU.\n
/// D3D11 counterpart: D3D11_MAP_WRITE_NO_OVERWRITE. OpenGL counterpart: GL_MAP_UNSYNCHRONIZED_BIT
MAP_FLAG_NO_OVERWRITE = 0x004
};
DEFINE_FLAG_ENUM_OPERATORS(MAP_FLAGS)
/// Describes resource dimension
/// This enumeration is used by
/// - TextureDesc to describe texture type
/// - TextureViewDesc to describe texture view type
DILIGENT_TYPED_ENUM(RESOURCE_DIMENSION, Uint8)
{
RESOURCE_DIM_UNDEFINED = 0, ///< Texture type undefined
RESOURCE_DIM_BUFFER, ///< Buffer
RESOURCE_DIM_TEX_1D, ///< One-dimensional texture
RESOURCE_DIM_TEX_1D_ARRAY, ///< One-dimensional texture array
RESOURCE_DIM_TEX_2D, ///< Two-dimensional texture
RESOURCE_DIM_TEX_2D_ARRAY, ///< Two-dimensional texture array
RESOURCE_DIM_TEX_3D, ///< Three-dimensional texture
RESOURCE_DIM_TEX_CUBE, ///< Cube-map texture
RESOURCE_DIM_TEX_CUBE_ARRAY, ///< Cube-map array texture
RESOURCE_DIM_NUM_DIMENSIONS ///< Helper value that stores the total number of texture types in the enumeration
};
/// Texture view type
/// This enumeration describes allowed view types for a texture view. It is used by TextureViewDesc
/// structure.
DILIGENT_TYPED_ENUM(TEXTURE_VIEW_TYPE, Uint8)
{
/// Undefined view type
TEXTURE_VIEW_UNDEFINED = 0,
/// A texture view will define a shader resource view that will be used
/// as the source for the shader read operations
TEXTURE_VIEW_SHADER_RESOURCE,
/// A texture view will define a render target view that will be used
/// as the target for rendering operations
TEXTURE_VIEW_RENDER_TARGET,
/// A texture view will define a depth stencil view that will be used
/// as the target for rendering operations
TEXTURE_VIEW_DEPTH_STENCIL,
/// A texture view will define an unordered access view that will be used
/// for unordered read/write operations from the shaders
TEXTURE_VIEW_UNORDERED_ACCESS,
/// Helper value that stores that total number of texture views
TEXTURE_VIEW_NUM_VIEWS
};
/// Buffer view type
/// This enumeration describes allowed view types for a buffer view. It is used by BufferViewDesc
/// structure.
DILIGENT_TYPED_ENUM(BUFFER_VIEW_TYPE, Uint8)
{
/// Undefined view type
BUFFER_VIEW_UNDEFINED = 0,
/// A buffer view will define a shader resource view that will be used
/// as the source for the shader read operations
BUFFER_VIEW_SHADER_RESOURCE,
/// A buffer view will define an unordered access view that will be used
/// for unordered read/write operations from the shaders
BUFFER_VIEW_UNORDERED_ACCESS,
/// Helper value that stores that total number of buffer views
BUFFER_VIEW_NUM_VIEWS
};
/// Texture formats
/// This enumeration describes available texture formats and generally mirrors DXGI_FORMAT enumeration.
/// The table below provides detailed information on each format. Most of the formats are widely supported
/// by all modern APIs (DX10+, OpenGL3.3+ and OpenGLES3.0+). Specific requirements are additionally indicated.
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx">DXGI_FORMAT enumeration on MSDN</a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format">OpenGL Texture Formats</a>
///
DILIGENT_TYPED_ENUM(TEXTURE_FORMAT, Uint16)
{
/// Unknown format
TEX_FORMAT_UNKNOWN = 0,
/// Four-component 128-bit typeless format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32A32_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA32F is used.
TEX_FORMAT_RGBA32_TYPELESS,
/// Four-component 128-bit floating-point format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32A32_FLOAT. OpenGL counterpart: GL_RGBA32F.
TEX_FORMAT_RGBA32_FLOAT,
/// Four-component 128-bit unsigned-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32A32_UINT. OpenGL counterpart: GL_RGBA32UI.
TEX_FORMAT_RGBA32_UINT,
/// Four-component 128-bit signed-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32A32_SINT. OpenGL counterpart: GL_RGBA32I.
TEX_FORMAT_RGBA32_SINT,
/// Three-component 96-bit typeless format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32_TYPELESS. OpenGL does not have direct counterpart, GL_RGB32F is used.
/// \warning This format has weak hardware support and is not recommended
TEX_FORMAT_RGB32_TYPELESS,
/// Three-component 96-bit floating-point format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32_FLOAT. OpenGL counterpart: GL_RGB32F.
/// \warning This format has weak hardware support and is not recommended
TEX_FORMAT_RGB32_FLOAT,
/// Three-component 96-bit unsigned-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32_UINT. OpenGL counterpart: GL_RGB32UI.
/// \warning This format has weak hardware support and is not recommended
TEX_FORMAT_RGB32_UINT,
/// Three-component 96-bit signed-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32B32_SINT. OpenGL counterpart: GL_RGB32I.
/// \warning This format has weak hardware support and is not recommended
TEX_FORMAT_RGB32_SINT,
/// Four-component 64-bit typeless format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA16F is used.
TEX_FORMAT_RGBA16_TYPELESS,
/// Four-component 64-bit half-precision floating-point format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_FLOAT. OpenGL counterpart: GL_RGBA16F.
TEX_FORMAT_RGBA16_FLOAT,
/// Four-component 64-bit unsigned-normalized-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_UNORM. OpenGL counterpart: GL_RGBA16. \n
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_RGBA16_UNORM,
/// Four-component 64-bit unsigned-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_UINT. OpenGL counterpart: GL_RGBA16UI.
TEX_FORMAT_RGBA16_UINT,
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// Four-component 64-bit signed-normalized-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_SNORM. OpenGL counterpart: GL_RGBA16_SNORM. \n
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_RGBA16_SNORM,
/// Four-component 64-bit signed-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16B16A16_SINT. OpenGL counterpart: GL_RGBA16I.
TEX_FORMAT_RGBA16_SINT,
/// Two-component 64-bit typeless format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32_TYPELESS. OpenGL does not have direct counterpart, GL_RG32F is used.
TEX_FORMAT_RG32_TYPELESS,
/// Two-component 64-bit floating-point format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32_FLOAT. OpenGL counterpart: GL_RG32F.
TEX_FORMAT_RG32_FLOAT,
/// Two-component 64-bit unsigned-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32_UINT. OpenGL counterpart: GL_RG32UI.
TEX_FORMAT_RG32_UINT,
/// Two-component 64-bit signed-integer format with 32-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R32G32_SINT. OpenGL counterpart: GL_RG32I.
TEX_FORMAT_RG32_SINT,
/// Two-component 64-bit typeless format with 32-bits for R channel and 8 bits for G channel. \n
/// D3D counterpart: DXGI_FORMAT_R32G8X24_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH32F_STENCIL8 is used.
TEX_FORMAT_R32G8X24_TYPELESS,
/// Two-component 64-bit format with 32-bit floating-point depth channel and 8-bit stencil channel. \n
/// D3D counterpart: DXGI_FORMAT_D32_FLOAT_S8X24_UINT. OpenGL counterpart: GL_DEPTH32F_STENCIL8.
TEX_FORMAT_D32_FLOAT_S8X24_UINT,
/// Two-component 64-bit format with 32-bit floating-point R channel and 8+24-bits of typeless data. \n
/// D3D counterpart: DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH32F_STENCIL8 is used.
TEX_FORMAT_R32_FLOAT_X8X24_TYPELESS,
/// Two-component 64-bit format with 32-bit typeless data and 8-bit G channel. \n
/// D3D counterpart: DXGI_FORMAT_X32_TYPELESS_G8X24_UINT
/// \warning This format is currently not implemented in OpenGL version
TEX_FORMAT_X32_TYPELESS_G8X24_UINT,
/// Four-component 32-bit typeless format with 10 bits for RGB and 2 bits for alpha channel. \n
/// D3D counterpart: DXGI_FORMAT_R10G10B10A2_TYPELESS. OpenGL does not have direct counterpart, GL_RGB10_A2 is used.
TEX_FORMAT_RGB10A2_TYPELESS,
/// Four-component 32-bit unsigned-normalized-integer format with 10 bits for each color and 2 bits for alpha channel. \n
/// D3D counterpart: DXGI_FORMAT_R10G10B10A2_UNORM. OpenGL counterpart: GL_RGB10_A2.
TEX_FORMAT_RGB10A2_UNORM,
/// Four-component 32-bit unsigned-integer format with 10 bits for each color and 2 bits for alpha channel. \n
/// D3D counterpart: DXGI_FORMAT_R10G10B10A2_UINT. OpenGL counterpart: GL_RGB10_A2UI.
TEX_FORMAT_RGB10A2_UINT,
/// Three-component 32-bit format encoding three partial precision channels using 11 bits for red and green and 10 bits for blue channel. \n
/// D3D counterpart: DXGI_FORMAT_R11G11B10_FLOAT. OpenGL counterpart: GL_R11F_G11F_B10F.
TEX_FORMAT_R11G11B10_FLOAT,
/// Four-component 32-bit typeless format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_TYPELESS. OpenGL does not have direct counterpart, GL_RGBA8 is used.
TEX_FORMAT_RGBA8_TYPELESS,
/// Four-component 32-bit unsigned-normalized-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UNORM. OpenGL counterpart: GL_RGBA8.
TEX_FORMAT_RGBA8_UNORM,
/// Four-component 32-bit unsigned-normalized-integer sRGB format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UNORM_SRGB. OpenGL counterpart: GL_SRGB8_ALPHA8.
TEX_FORMAT_RGBA8_UNORM_SRGB,
/// Four-component 32-bit unsigned-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_UINT. OpenGL counterpart: GL_RGBA8UI.
TEX_FORMAT_RGBA8_UINT,
/// Four-component 32-bit signed-normalized-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_SNORM. OpenGL counterpart: GL_RGBA8_SNORM.
TEX_FORMAT_RGBA8_SNORM,
/// Four-component 32-bit signed-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8B8A8_SINT. OpenGL counterpart: GL_RGBA8I.
TEX_FORMAT_RGBA8_SINT,
/// Two-component 32-bit typeless format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_TYPELESS. OpenGL does not have direct counterpart, GL_RG16F is used.
TEX_FORMAT_RG16_TYPELESS,
/// Two-component 32-bit half-precision floating-point format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_FLOAT. OpenGL counterpart: GL_RG16F.
TEX_FORMAT_RG16_FLOAT,
/// Two-component 32-bit unsigned-normalized-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_UNORM. OpenGL counterpart: GL_RG16. \n
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_RG16_UNORM,
/// Two-component 32-bit unsigned-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_UINT. OpenGL counterpart: GL_RG16UI.
TEX_FORMAT_RG16_UINT,
/// Two-component 32-bit signed-normalized-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_SNORM. OpenGL counterpart: GL_RG16_SNORM. \n
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_RG16_SNORM,
/// Two-component 32-bit signed-integer format with 16-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R16G16_SINT. OpenGL counterpart: GL_RG16I.
TEX_FORMAT_RG16_SINT,
/// Single-component 32-bit typeless format. \n
/// D3D counterpart: DXGI_FORMAT_R32_TYPELESS. OpenGL does not have direct counterpart, GL_R32F is used.
TEX_FORMAT_R32_TYPELESS,
/// Single-component 32-bit floating-point depth format. \n
/// D3D counterpart: DXGI_FORMAT_D32_FLOAT. OpenGL counterpart: GL_DEPTH_COMPONENT32F.
TEX_FORMAT_D32_FLOAT,
/// Single-component 32-bit floating-point format. \n
/// D3D counterpart: DXGI_FORMAT_R32_FLOAT. OpenGL counterpart: GL_R32F.
TEX_FORMAT_R32_FLOAT,
/// Single-component 32-bit unsigned-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R32_UINT. OpenGL counterpart: GL_R32UI.
TEX_FORMAT_R32_UINT,
/// Single-component 32-bit signed-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R32_SINT. OpenGL counterpart: GL_R32I.
TEX_FORMAT_R32_SINT,
/// Two-component 32-bit typeless format with 24 bits for R and 8 bits for G channel. \n
/// D3D counterpart: DXGI_FORMAT_R24G8_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH24_STENCIL8 is used.
TEX_FORMAT_R24G8_TYPELESS,
/// Two-component 32-bit format with 24 bits for unsigned-normalized-integer depth and 8 bits for stencil. \n
/// D3D counterpart: DXGI_FORMAT_D24_UNORM_S8_UINT. OpenGL counterpart: GL_DEPTH24_STENCIL8.
TEX_FORMAT_D24_UNORM_S8_UINT,
/// Two-component 32-bit format with 24 bits for unsigned-normalized-integer data and 8 bits of unreferenced data. \n
/// D3D counterpart: DXGI_FORMAT_R24_UNORM_X8_TYPELESS. OpenGL does not have direct counterpart, GL_DEPTH24_STENCIL8 is used.
TEX_FORMAT_R24_UNORM_X8_TYPELESS,
/// Two-component 32-bit format with 24 bits of unreferenced data and 8 bits of unsigned-integer data. \n
/// D3D counterpart: DXGI_FORMAT_X24_TYPELESS_G8_UINT
/// \warning This format is currently not implemented in OpenGL version
TEX_FORMAT_X24_TYPELESS_G8_UINT,
/// Two-component 16-bit typeless format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_TYPELESS. OpenGL does not have direct counterpart, GL_RG8 is used.
TEX_FORMAT_RG8_TYPELESS,
/// Two-component 16-bit unsigned-normalized-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_UNORM. OpenGL counterpart: GL_RG8.
TEX_FORMAT_RG8_UNORM,
/// Two-component 16-bit unsigned-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_UINT. OpenGL counterpart: GL_RG8UI.
TEX_FORMAT_RG8_UINT,
/// Two-component 16-bit signed-normalized-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_SNORM. OpenGL counterpart: GL_RG8_SNORM.
TEX_FORMAT_RG8_SNORM,
/// Two-component 16-bit signed-integer format with 8-bit channels. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_SINT. OpenGL counterpart: GL_RG8I.
TEX_FORMAT_RG8_SINT,
/// Single-component 16-bit typeless format. \n
/// D3D counterpart: DXGI_FORMAT_R16_TYPELESS. OpenGL does not have direct counterpart, GL_R16F is used.
TEX_FORMAT_R16_TYPELESS,
/// Single-component 16-bit half-precisoin floating-point format. \n
/// D3D counterpart: DXGI_FORMAT_R16_FLOAT. OpenGL counterpart: GL_R16F.
TEX_FORMAT_R16_FLOAT,
/// Single-component 16-bit unsigned-normalized-integer depth format. \n
/// D3D counterpart: DXGI_FORMAT_D16_UNORM. OpenGL counterpart: GL_DEPTH_COMPONENT16.
TEX_FORMAT_D16_UNORM,
/// Single-component 16-bit unsigned-normalized-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R16_UNORM. OpenGL counterpart: GL_R16.
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_R16_UNORM,
/// Single-component 16-bit unsigned-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R16_UINT. OpenGL counterpart: GL_R16UI.
TEX_FORMAT_R16_UINT,
/// Single-component 16-bit signed-normalized-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R16_SNORM. OpenGL counterpart: GL_R16_SNORM. \n
/// [GL_EXT_texture_norm16]: https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_norm16.txt
/// OpenGLES: [GL_EXT_texture_norm16][] extension is required
TEX_FORMAT_R16_SNORM,
/// Single-component 16-bit signed-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R16_SINT. OpenGL counterpart: GL_R16I.
TEX_FORMAT_R16_SINT,
/// Single-component 8-bit typeless format. \n
/// D3D counterpart: DXGI_FORMAT_R8_TYPELESS. OpenGL does not have direct counterpart, GL_R8 is used.
TEX_FORMAT_R8_TYPELESS,
/// Single-component 8-bit unsigned-normalized-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R8_UNORM. OpenGL counterpart: GL_R8.
TEX_FORMAT_R8_UNORM,
/// Single-component 8-bit unsigned-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R8_UINT. OpenGL counterpart: GL_R8UI.
TEX_FORMAT_R8_UINT,
/// Single-component 8-bit signed-normalized-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R8_SNORM. OpenGL counterpart: GL_R8_SNORM.
TEX_FORMAT_R8_SNORM,
/// Single-component 8-bit signed-integer format. \n
/// D3D counterpart: DXGI_FORMAT_R8_SINT. OpenGL counterpart: GL_R8I.
TEX_FORMAT_R8_SINT,
/// Single-component 8-bit unsigned-normalized-integer format for alpha only. \n
/// D3D counterpart: DXGI_FORMAT_A8_UNORM
/// \warning This format is not availanle in OpenGL
TEX_FORMAT_A8_UNORM,
/// Single-component 1-bit format. \n
/// D3D counterpart: DXGI_FORMAT_R1_UNORM
/// \warning This format is not availanle in OpenGL
TEX_FORMAT_R1_UNORM,
/// Three partial-precision floating pointer numbers sharing single exponent encoded into a 32-bit value. \n
/// D3D counterpart: DXGI_FORMAT_R9G9B9E5_SHAREDEXP. OpenGL counterpart: GL_RGB9_E5.
TEX_FORMAT_RGB9E5_SHAREDEXP,
/// Four-component unsigned-normalized integer format analogous to UYVY encoding. \n
/// D3D counterpart: DXGI_FORMAT_R8G8_B8G8_UNORM
/// \warning This format is not availanle in OpenGL
TEX_FORMAT_RG8_B8G8_UNORM,
/// Four-component unsigned-normalized integer format analogous to YUY2 encoding. \n
/// D3D counterpart: DXGI_FORMAT_G8R8_G8B8_UNORM
/// \warning This format is not availanle in OpenGL
TEX_FORMAT_G8R8_G8B8_UNORM,
/// Four-component typeless block-compression format with 1:8 compression ratio.\n
/// D3D counterpart: DXGI_FORMAT_BC1_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGB_S3TC_DXT1_EXT is used. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a>
TEX_FORMAT_BC1_TYPELESS,
/// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 0 or 1 bit for A channel.
/// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:8 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC1_UNORM. OpenGL counterpart: GL_COMPRESSED_RGB_S3TC_DXT1_EXT.\n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a>
TEX_FORMAT_BC1_UNORM,
/// Four-component unsigned-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 0 or 1 bit for A channel. \n
/// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:8 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC1_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_S3TC_DXT1_EXT.\n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC1">BC1 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT1_Format">DXT1 on OpenGL.org </a>
TEX_FORMAT_BC1_UNORM_SRGB,
/// Four component typeless block-compression format with 1:4 compression ratio.\n
/// D3D counterpart: DXGI_FORMAT_BC2_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT is used. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a>
TEX_FORMAT_BC2_TYPELESS,
/// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 4 bits for low-coherent separate A channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC2_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a>
TEX_FORMAT_BC2_UNORM,
/// Four-component signed-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 4 bits for low-coherent separate A channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC2_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC2">BC2 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT3_Format">DXT3 on OpenGL.org </a>
TEX_FORMAT_BC2_UNORM_SRGB,
/// Four-component typeless block-compression format with 1:4 compression ratio.\n
/// D3D counterpart: DXGI_FORMAT_BC3_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT is used. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a>
TEX_FORMAT_BC3_TYPELESS,
/// Four-component unsigned-normalized-integer block-compression format with 5 bits for R, 6 bits for G, 5 bits for B, and 8 bits for highly-coherent A channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC3_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a>
TEX_FORMAT_BC3_UNORM,
/// Four-component unsigned-normalized-integer block-compression sRGB format with 5 bits for R, 6 bits for G, 5 bits for B, and 8 bits for highly-coherent A channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:4 compression ratio against RGBA8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC3_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT. \n
/// [GL_EXT_texture_compression_s3tc]: https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt
/// OpenGL & OpenGLES: [GL_EXT_texture_compression_s3tc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC3">BC3 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/S3_Texture_Compression#DXT5_Format">DXT5 on OpenGL.org </a>
TEX_FORMAT_BC3_UNORM_SRGB,
/// One-component typeless block-compression format with 1:2 compression ratio. \n
/// D3D counterpart: DXGI_FORMAT_BC4_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RED_RGTC1 is used. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC4_TYPELESS,
/// One-component unsigned-normalized-integer block-compression format with 8 bits for R channel.
/// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:2 compression ratio against R8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC4_UNORM. OpenGL counterpart: GL_COMPRESSED_RED_RGTC1. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC4_UNORM,
/// One-component signed-normalized-integer block-compression format with 8 bits for R channel.
/// The pixel data is encoded using 8 bytes per 4x4 block (4 bits per pixel) providing 1:2 compression ratio against R8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC4_SNORM. OpenGL counterpart: GL_COMPRESSED_SIGNED_RED_RGTC1. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC4">BC4 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC4_SNORM,
/// Two-component typeless block-compression format with 1:2 compression ratio. \n
/// D3D counterpart: DXGI_FORMAT_BC5_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RG_RGTC2 is used. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC5_TYPELESS,
/// Two-component unsigned-normalized-integer block-compression format with 8 bits for R and 8 bits for G channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:2 compression ratio against RG8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC5_UNORM. OpenGL counterpart: GL_COMPRESSED_RG_RGTC2. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC5_UNORM,
/// Two-component signed-normalized-integer block-compression format with 8 bits for R and 8 bits for G channel.
/// The pixel data is encoded using 16 bytes per 4x4 block (8 bits per pixel) providing 1:2 compression ratio against RG8 format. \n
/// D3D counterpart: DXGI_FORMAT_BC5_SNORM. OpenGL counterpart: GL_COMPRESSED_SIGNED_RG_RGTC2. \n
/// [GL_ARB_texture_compression_rgtc]: https://www.opengl.org/registry/specs/ARB/texture_compression_rgtc.txt
/// OpenGL & OpenGLES: [GL_ARB_texture_compression_rgtc][] extension is required
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb694531(v=vs.85).aspx#BC5">BC5 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/Image_Format#Compressed_formats">Compressed formats on OpenGL.org </a>
TEX_FORMAT_BC5_SNORM,
/// Three-component 16-bit unsigned-normalized-integer format with 5 bits for blue, 6 bits for green, and 5 bits for red channel. \n
/// D3D counterpart: DXGI_FORMAT_B5G6R5_UNORM
/// \warning This format is not available until D3D11.1 and Windows 8. It is also not available in OpenGL
TEX_FORMAT_B5G6R5_UNORM,
/// Four-component 16-bit unsigned-normalized-integer format with 5 bits for each color channel and 1-bit alpha. \n
/// D3D counterpart: DXGI_FORMAT_B5G5R5A1_UNORM
/// \warning This format is not available until D3D11.1 and Windows 8. It is also not available in OpenGL
TEX_FORMAT_B5G5R5A1_UNORM,
/// Four-component 32-bit unsigned-normalized-integer format with 8 bits for each channel. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8A8_UNORM.
/// \warning This format is not available in OpenGL
TEX_FORMAT_BGRA8_UNORM,
/// Four-component 32-bit unsigned-normalized-integer format with 8 bits for each color channel and 8 bits unused. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8X8_UNORM.
/// \warning This format is not available in OpenGL
TEX_FORMAT_BGRX8_UNORM,
/// Four-component 32-bit 2.8-biased fixed-point format with 10 bits for each color channel and 2-bit alpha. \n
/// D3D counterpart: DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM.
/// \warning This format is not available in OpenGL
TEX_FORMAT_R10G10B10_XR_BIAS_A2_UNORM,
/// Four-component 32-bit typeless format with 8 bits for each channel. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8A8_TYPELESS.
/// \warning This format is not available in OpenGL
TEX_FORMAT_BGRA8_TYPELESS,
/// Four-component 32-bit unsigned-normalized sRGB format with 8 bits for each channel. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8A8_UNORM_SRGB.
/// \warning This format is not available in OpenGL.
TEX_FORMAT_BGRA8_UNORM_SRGB,
/// Four-component 32-bit typeless format that with 8 bits for each color channel, and 8 bits are unused. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8X8_TYPELESS.
/// \warning This format is not available in OpenGL.
TEX_FORMAT_BGRX8_TYPELESS,
/// Four-component 32-bit unsigned-normalized sRGB format with 8 bits for each color channel, and 8 bits are unused. \n
/// D3D counterpart: DXGI_FORMAT_B8G8R8X8_UNORM_SRGB.
/// \warning This format is not available in OpenGL.
TEX_FORMAT_BGRX8_UNORM_SRGB,
/// Three-component typeless block-compression format. \n
/// D3D counterpart: DXGI_FORMAT_BC6H_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT is used. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC6H_TYPELESS,
/// Three-component unsigned half-precision floating-point format with 16 bits for each channel. \n
/// D3D counterpart: DXGI_FORMAT_BC6H_UF16. OpenGL counterpart: GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC6H_UF16,
/// Three-channel signed half-precision floating-point format with 16 bits per each channel. \n
/// D3D counterpart: DXGI_FORMAT_BC6H_SF16. OpenGL counterpart: GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx">BC6H on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC6H_SF16,
/// Three-component typeless block-compression format. \n
/// D3D counterpart: DXGI_FORMAT_BC7_TYPELESS. OpenGL does not have direct counterpart, GL_COMPRESSED_RGBA_BPTC_UNORM is used. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC7_TYPELESS,
/// Three-component block-compression unsigned-normalized-integer format with 4 to 7 bits per color channel and 0 to 8 bits of alpha. \n
/// D3D counterpart: DXGI_FORMAT_BC7_UNORM. OpenGL counterpart: GL_COMPRESSED_RGBA_BPTC_UNORM. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC7_UNORM,
/// Three-component block-compression unsigned-normalized-integer sRGB format with 4 to 7 bits per color channel and 0 to 8 bits of alpha. \n
/// D3D counterpart: DXGI_FORMAT_BC7_UNORM_SRGB. OpenGL counterpart: GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM. \n
/// [GL_ARB_texture_compression_bptc]: https://cvs.khronos.org/svn/repos/ogl/trunk/doc/registry/public/specs/ARB/texture_compression_bptc.txt
/// OpenGL: [GL_ARB_texture_compression_bptc][] extension is required. Not supported in at least OpenGLES3.1
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh308953(v=vs.85).aspx">BC7 on MSDN </a>,
/// <a href = "https://www.opengl.org/wiki/BPTC_Texture_Compression">BPTC Texture Compression on OpenGL.org </a>
TEX_FORMAT_BC7_UNORM_SRGB,
/// Helper member containing the total number of texture formats in the enumeration
TEX_FORMAT_NUM_FORMATS
};
/// Filter type
/// This enumeration defines filter type. It is used by SamplerDesc structure to define min, mag and mip filters.
/// \note On D3D11, comparison filters only work with textures that have the following formats:
/// R32_FLOAT_X8X24_TYPELESS, R32_FLOAT, R24_UNORM_X8_TYPELESS, R16_UNORM.
DILIGENT_TYPED_ENUM(FILTER_TYPE, Uint8)
{
FILTER_TYPE_UNKNOWN = 0, ///< Unknown filter type
FILTER_TYPE_POINT, ///< Point filtering
FILTER_TYPE_LINEAR, ///< Linear filtering
FILTER_TYPE_ANISOTROPIC, ///< Anisotropic filtering
FILTER_TYPE_COMPARISON_POINT, ///< Comparison-point filtering
FILTER_TYPE_COMPARISON_LINEAR, ///< Comparison-linear filtering
FILTER_TYPE_COMPARISON_ANISOTROPIC, ///< Comparison-anisotropic filtering
FILTER_TYPE_MINIMUM_POINT, ///< Minimum-point filtering (DX12 only)
FILTER_TYPE_MINIMUM_LINEAR, ///< Minimum-linear filtering (DX12 only)
FILTER_TYPE_MINIMUM_ANISOTROPIC, ///< Minimum-anisotropic filtering (DX12 only)
FILTER_TYPE_MAXIMUM_POINT, ///< Maximum-point filtering (DX12 only)
FILTER_TYPE_MAXIMUM_LINEAR, ///< Maximum-linear filtering (DX12 only)
FILTER_TYPE_MAXIMUM_ANISOTROPIC, ///< Maximum-anisotropic filtering (DX12 only)
FILTER_TYPE_NUM_FILTERS ///< Helper value that stores the total number of filter types in the enumeration
};
/// Texture address mode
/// [D3D11_TEXTURE_ADDRESS_MODE]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476256(v=vs.85).aspx
/// [D3D12_TEXTURE_ADDRESS_MODE]: https://msdn.microsoft.com/en-us/library/windows/desktop/dn770441(v=vs.85).aspx
/// Defines a technique for resolving texture coordinates that are outside of
/// the boundaries of a texture. The enumeration generally mirrors [D3D11_TEXTURE_ADDRESS_MODE][]/[D3D12_TEXTURE_ADDRESS_MODE][] enumeration.
/// It is used by SamplerDesc structure to define the address mode for U,V and W texture coordinates.
DILIGENT_TYPED_ENUM(TEXTURE_ADDRESS_MODE, Uint8)
{
/// Unknown mode
TEXTURE_ADDRESS_UNKNOWN = 0,
/// Tile the texture at every integer junction. \n
/// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_WRAP/D3D12_TEXTURE_ADDRESS_MODE_WRAP. OpenGL counterpart: GL_REPEAT
TEXTURE_ADDRESS_WRAP = 1,
/// Flip the texture at every integer junction. \n
/// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_MIRROR/D3D12_TEXTURE_ADDRESS_MODE_MIRROR. OpenGL counterpart: GL_MIRRORED_REPEAT
TEXTURE_ADDRESS_MIRROR = 2,
/// Texture coordinates outside the range [0.0, 1.0] are set to the
/// texture color at 0.0 or 1.0, respectively. \n
/// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_CLAMP/D3D12_TEXTURE_ADDRESS_MODE_CLAMP. OpenGL counterpart: GL_CLAMP_TO_EDGE
TEXTURE_ADDRESS_CLAMP = 3,
/// Texture coordinates outside the range [0.0, 1.0] are set to the border color specified
/// specified in SamplerDesc structure. \n
/// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_BORDER/D3D12_TEXTURE_ADDRESS_MODE_BORDER. OpenGL counterpart: GL_CLAMP_TO_BORDER
TEXTURE_ADDRESS_BORDER = 4,
/// Similar to TEXTURE_ADDRESS_MIRROR and TEXTURE_ADDRESS_CLAMP. Takes the absolute
/// value of the texture coordinate (thus, mirroring around 0), and then clamps to
/// the maximum value. \n
/// Direct3D Counterpart: D3D11_TEXTURE_ADDRESS_MIRROR_ONCE/D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE. OpenGL counterpart: GL_MIRROR_CLAMP_TO_EDGE
/// \note GL_MIRROR_CLAMP_TO_EDGE is only available in OpenGL4.4+, and is not available until at least OpenGLES3.1
TEXTURE_ADDRESS_MIRROR_ONCE = 5,
/// Helper value that stores the total number of texture address modes in the enumeration
TEXTURE_ADDRESS_NUM_MODES
};
/// Comparison function
/// [D3D11_COMPARISON_FUNC]: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476101(v=vs.85).aspx
/// [D3D12_COMPARISON_FUNC]: https://msdn.microsoft.com/en-us/library/windows/desktop/dn770349(v=vs.85).aspx
/// This enumeartion defines a comparison function. It generally mirrors [D3D11_COMPARISON_FUNC]/[D3D12_COMPARISON_FUNC] enum and is used by
/// - SamplerDesc to define a comparison function if one of the comparison mode filters is used
/// - StencilOpDesc to define a stencil function
/// - DepthStencilStateDesc to define a depth function
DILIGENT_TYPED_ENUM(COMPARISON_FUNCTION, Uint8)
{
/// Unknown comparison function
COMPARISON_FUNC_UNKNOWN = 0,
/// Comparison never passes. \n
/// Direct3D counterpart: D3D11_COMPARISON_NEVER/D3D12_COMPARISON_FUNC_NEVER. OpenGL counterpart: GL_NEVER.
COMPARISON_FUNC_NEVER,
/// Comparison passes if the source data is less than the destination data.\n
/// Direct3D counterpart: D3D11_COMPARISON_LESS/D3D12_COMPARISON_FUNC_LESS. OpenGL counterpart: GL_LESS.
COMPARISON_FUNC_LESS,
/// Comparison passes if the source data is equal to the destination data.\n
/// Direct3D counterpart: D3D11_COMPARISON_EQUAL/D3D12_COMPARISON_FUNC_EQUAL. OpenGL counterpart: GL_EQUAL.
COMPARISON_FUNC_EQUAL,
/// Comparison passes if the source data is less than or equal to the destination data.\n
/// Direct3D counterpart: D3D11_COMPARISON_LESS_EQUAL/D3D12_COMPARISON_FUNC_LESS_EQUAL. OpenGL counterpart: GL_LEQUAL.
COMPARISON_FUNC_LESS_EQUAL,
/// Comparison passes if the source data is greater than the destination data.\n
/// Direct3D counterpart: 3D11_COMPARISON_GREATER/D3D12_COMPARISON_FUNC_GREATER. OpenGL counterpart: GL_GREATER.
COMPARISON_FUNC_GREATER,
/// Comparison passes if the source data is not equal to the destination data.\n
/// Direct3D counterpart: D3D11_COMPARISON_NOT_EQUAL/D3D12_COMPARISON_FUNC_NOT_EQUAL. OpenGL counterpart: GL_NOTEQUAL.
COMPARISON_FUNC_NOT_EQUAL,
/// Comparison passes if the source data is greater than or equal to the destination data.\n
/// Direct3D counterpart: D3D11_COMPARISON_GREATER_EQUAL/D3D12_COMPARISON_FUNC_GREATER_EQUAL. OpenGL counterpart: GL_GEQUAL.
COMPARISON_FUNC_GREATER_EQUAL,
/// Comparison always passes. \n
/// Direct3D counterpart: D3D11_COMPARISON_ALWAYS/D3D12_COMPARISON_FUNC_ALWAYS. OpenGL counterpart: GL_ALWAYS.
COMPARISON_FUNC_ALWAYS,
/// Helper value that stores the total number of comparison functions in the enumeration
COMPARISON_FUNC_NUM_FUNCTIONS
};
/// Miscellaneous texture flags
/// The enumeration is used by TextureDesc to describe misc texture flags
DILIGENT_TYPED_ENUM(MISC_TEXTURE_FLAGS, Uint8)
{
MISC_TEXTURE_FLAG_NONE = 0x00,
/// Allow automatic mipmap generation with ITextureView::GenerateMips()
/// \note A texture must be created with BIND_RENDER_TARGET bind flag
MISC_TEXTURE_FLAG_GENERATE_MIPS = 0x01
};
DEFINE_FLAG_ENUM_OPERATORS(MISC_TEXTURE_FLAGS)
/// Input primitive topology.
/// This enumeration is used by DrawAttribs structure to define input primitive topology.
DILIGENT_TYPED_ENUM(PRIMITIVE_TOPOLOGY, Uint8)
{
/// Undefined topology
PRIMITIVE_TOPOLOGY_UNDEFINED = 0,
/// Interpret the vertex data as a list of triangles.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST. OpenGL counterpart: GL_TRIANGLES.
PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
/// Interpret the vertex data as a triangle strip.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP. OpenGL counterpart: GL_TRIANGLE_STRIP.
PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
/// Interpret the vertex data as a list of points.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_POINTLIST. OpenGL counterpart: GL_POINTS.
PRIMITIVE_TOPOLOGY_POINT_LIST,
/// Interpret the vertex data as a list of lines.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_LINELIST. OpenGL counterpart: GL_LINES.
PRIMITIVE_TOPOLOGY_LINE_LIST,
/// Interpret the vertex data as a line strip.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_LINESTRIP. OpenGL counterpart: GL_LINE_STRIP.
PRIMITIVE_TOPOLOGY_LINE_STRIP,
/// Interpret the vertex data as a list of one control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of two control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of three control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of four control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of five control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of six control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of seven control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of eight control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of nine control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of ten control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 11 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 12 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 13 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 14 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 15 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 16 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 17 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 18 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 19 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 20 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 21 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 22 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 23 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 24 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 25 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 26 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 27 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 28 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 29 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 30 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 31 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST,
/// Interpret the vertex data as a list of 32 control point patches.\n
/// D3D counterpart: D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST. OpenGL counterpart: GL_PATCHES.
PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST,
/// Helper value that stores the total number of topologies in the enumeration
PRIMITIVE_TOPOLOGY_NUM_TOPOLOGIES
};
/// Describes common device object attributes
struct DeviceObjectAttribs
{
/// Object name
const Char* Name DEFAULT_INITIALIZER(nullptr);
// We have to explicitly define constructors because otherwise Apple's clang fails to compile the following legitimate code:
// DeviceObjectAttribs{"Name"}
#if DILIGENT_CPP_INTERFACE
DeviceObjectAttribs()noexcept{}
explicit DeviceObjectAttribs(const Char* _Name) :
Name{_Name}
{}
#endif
};
typedef struct DeviceObjectAttribs DeviceObjectAttribs;
/// Hardware adapter type
DILIGENT_TYPED_ENUM(ADAPTER_TYPE, Uint8)
{
/// Adapter type is unknown
ADAPTER_TYPE_UNKNOWN = 0,
/// Software adapter
ADAPTER_TYPE_SOFTWARE,
/// Hardware adapter
ADAPTER_TYPE_HARDWARE
};
/// Adapter attributes
struct AdapterAttribs
{
/// Adapter type. See Diligent::ADAPTER_TYPE.
ADAPTER_TYPE AdapterType DEFAULT_INITIALIZER(ADAPTER_TYPE_UNKNOWN);
/// A string that contains the adapter description
char Description[128] DEFAULT_INITIALIZER({});
/// Dedicated video memory, in bytes
size_t DedicatedVideoMemory DEFAULT_INITIALIZER(0);
/// Dedicated system memory, in bytes
size_t DedicatedSystemMemory DEFAULT_INITIALIZER(0);
/// Dedicated shared memory, in bytes
size_t SharedSystemMemory DEFAULT_INITIALIZER(0);
/// The PCI ID of the hardware vendor
Uint32 VendorId DEFAULT_INITIALIZER(0);
/// The PCI ID of the hardware device
Uint32 DeviceId DEFAULT_INITIALIZER(0);
/// Number of outputs this device has
Uint32 NumOutputs DEFAULT_INITIALIZER(0);
};
typedef struct AdapterAttribs AdapterAttribs;
/// Flags indicating how an image is stretched to fit a given monitor's resolution.
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173066(v=vs.85).aspx">DXGI_MODE_SCALING enumeration on MSDN</a>,
enum SCALING_MODE
{
/// Unspecified scaling.
/// D3D Counterpart: DXGI_MODE_SCALING_UNSPECIFIED.
SCALING_MODE_UNSPECIFIED = 0,
/// Specifies no scaling. The image is centered on the display.
/// This flag is typically used for a fixed-dot-pitch display (such as an LED display).
/// D3D Counterpart: DXGI_MODE_SCALING_CENTERED.
SCALING_MODE_CENTERED = 1,
/// Specifies stretched scaling.
/// D3D Counterpart: DXGI_MODE_SCALING_STRETCHED.
SCALING_MODE_STRETCHED = 2
};
/// Flags indicating the method the raster uses to create an image on a surface.
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/bb173067">DXGI_MODE_SCANLINE_ORDER enumeration on MSDN</a>,
enum SCANLINE_ORDER
{
/// Scanline order is unspecified
/// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED.
SCANLINE_ORDER_UNSPECIFIED = 0,
/// The image is created from the first scanline to the last without skipping any
/// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE.
SCANLINE_ORDER_PROGRESSIVE = 1,
/// The image is created beginning with the upper field
/// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST.
SCANLINE_ORDER_UPPER_FIELD_FIRST = 2,
/// The image is created beginning with the lower field
/// D3D Counterpart: DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST.
SCANLINE_ORDER_LOWER_FIELD_FIRST = 3
};
/// Display mode attributes
struct DisplayModeAttribs
{
/// Display resolution width
Uint32 Width DEFAULT_INITIALIZER(0);
/// Display resolution height
Uint32 Height DEFAULT_INITIALIZER(0);
/// Display format
TEXTURE_FORMAT Format DEFAULT_INITIALIZER(TEX_FORMAT_UNKNOWN);
/// Refresh rate numerator
Uint32 RefreshRateNumerator DEFAULT_INITIALIZER(0);
/// Refresh rate denominator
Uint32 RefreshRateDenominator DEFAULT_INITIALIZER(0);
/// The scanline drawing mode.
enum SCALING_MODE Scaling DEFAULT_INITIALIZER(SCALING_MODE_UNSPECIFIED);
/// The scaling mode.
enum SCANLINE_ORDER ScanlineOrder DEFAULT_INITIALIZER(SCANLINE_ORDER_UNSPECIFIED);
};
typedef struct DisplayModeAttribs DisplayModeAttribs;
/// Defines allowed swap chain usage flags
DILIGENT_TYPED_ENUM(SWAP_CHAIN_USAGE_FLAGS, Uint32)
{
/// No allowed usage
SWAP_CHAIN_USAGE_NONE = 0x00L,
/// Swap chain can be used as render target ouput
SWAP_CHAIN_USAGE_RENDER_TARGET = 0x01L,
/// Swap chain images can be used as shader inputs
SWAP_CHAIN_USAGE_SHADER_INPUT = 0x02L,
/// Swap chain images can be used as source of copy operation
SWAP_CHAIN_USAGE_COPY_SOURCE = 0x04L
};
DEFINE_FLAG_ENUM_OPERATORS(SWAP_CHAIN_USAGE_FLAGS)
/// The transform applied to the image content prior to presentation.
DILIGENT_TYPED_ENUM(SURFACE_TRANSFORM, Uint32)
{
/// Uset the most optimal surface transform.
SURFACE_TRANSFORM_OPTIMAL = 0,
/// The image content is presented without being transformed.
SURFACE_TRANSFORM_IDENTITY,
/// The image content is rotated 90 degrees clockwise.
SURFACE_TRANSFORM_ROTATE_90,
/// The image content is rotated 180 degrees clockwise.
SURFACE_TRANSFORM_ROTATE_180,
/// The image content is rotated 270 degrees clockwise.
SURFACE_TRANSFORM_ROTATE_270,
/// The image content is mirrored horizontally.
SURFACE_TRANSFORM_HORIZONTAL_MIRROR,
/// The image content is mirrored horizontally, then rotated 90 degrees clockwise.
SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90,
/// The image content is mirrored horizontally, then rotated 180 degrees clockwise.
SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180,
/// The image content is mirrored horizontally, then rotated 270 degrees clockwise.
SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270
};
/// Swap chain description
struct SwapChainDesc
{
/// The swap chain width. Default value is 0
Uint32 Width DEFAULT_INITIALIZER(0);
/// The swap chain height. Default value is 0
Uint32 Height DEFAULT_INITIALIZER(0);
/// Back buffer format. Default value is Diligent::TEX_FORMAT_RGBA8_UNORM_SRGB
TEXTURE_FORMAT ColorBufferFormat DEFAULT_INITIALIZER(TEX_FORMAT_RGBA8_UNORM_SRGB);
/// Depth buffer format. Default value is Diligent::TEX_FORMAT_D32_FLOAT.
/// Use Diligent::TEX_FORMAT_UNKNOWN to create the swap chain without depth buffer.
TEXTURE_FORMAT DepthBufferFormat DEFAULT_INITIALIZER(TEX_FORMAT_D32_FLOAT);
/// Swap chain usage flags. Default value is Diligent::SWAP_CHAIN_USAGE_RENDER_TARGET
SWAP_CHAIN_USAGE_FLAGS Usage DEFAULT_INITIALIZER(SWAP_CHAIN_USAGE_RENDER_TARGET);
/// The transform, relative to the presentation engine's natural orientation,
/// applied to the image content prior to presentation.
///
/// \note When default value (SURFACE_TRANSFORM_OPTIMAL) is used, the engine will
/// select the most optimal surface transformation. An application may request
/// specific transform (e.g. SURFACE_TRANSFORM_IDENTITY) and the engine will
/// try to use that. However, if the transform is not available, the engine will
/// select the most optimal transform.
/// After the swap chain has been created, this member will contain the actual
/// transform selected by the engine and can be queried through ISwapChain::GetDesc()
/// method.
SURFACE_TRANSFORM PreTransform DEFAULT_INITIALIZER(SURFACE_TRANSFORM_OPTIMAL);
/// The number of buffers in the swap chain
Uint32 BufferCount DEFAULT_INITIALIZER(2);
/// Default depth value, which is used as optimized depth clear value in D3D12
Float32 DefaultDepthValue DEFAULT_INITIALIZER(1.f);
/// Default stencil value, which is used as optimized stencil clear value in D3D12
Uint8 DefaultStencilValue DEFAULT_INITIALIZER(0);
/// Indicates if this is a primary swap chain. When Present() is called
/// for the primary swap chain, the engine releases stale resources.
bool IsPrimary DEFAULT_INITIALIZER(true);
#if DILIGENT_CPP_INTERFACE
SwapChainDesc()noexcept{}
/// Constructor intializes the structure members with default values
SwapChainDesc(Uint32 _Width,
Uint32 _Height,
TEXTURE_FORMAT _ColorBufferFormat,
TEXTURE_FORMAT _DepthBufferFormat,
Uint32 _BufferCount = SwapChainDesc{}.BufferCount,
Float32 _DefaultDepthValue = SwapChainDesc{}.DefaultDepthValue,
Uint8 _DefaultStencilValue = SwapChainDesc{}.DefaultStencilValue,
bool _IsPrimary = SwapChainDesc{}.IsPrimary) :
Width {_Width },
Height {_Height },
ColorBufferFormat {_ColorBufferFormat },
DepthBufferFormat {_DepthBufferFormat },
BufferCount {_BufferCount },
DefaultDepthValue {_DefaultDepthValue },
DefaultStencilValue {_DefaultStencilValue},
IsPrimary {_IsPrimary }
{}
#endif
};
typedef struct SwapChainDesc SwapChainDesc;
/// Full screen mode description
/// \sa <a href = "https://msdn.microsoft.com/en-us/library/windows/desktop/hh404531(v=vs.85).aspx">DXGI_SWAP_CHAIN_FULLSCREEN_DESC structure on MSDN</a>,
struct FullScreenModeDesc
{
/// A Boolean value that specifies whether the swap chain is in fullscreen mode.
Bool Fullscreen DEFAULT_INITIALIZER(False);
/// Refresh rate numerator
Uint32 RefreshRateNumerator DEFAULT_INITIALIZER(0);
/// Refresh rate denominator
Uint32 RefreshRateDenominator DEFAULT_INITIALIZER(0);
/// The scanline drawing mode.
enum SCALING_MODE Scaling DEFAULT_INITIALIZER(SCALING_MODE_UNSPECIFIED);
/// The scaling mode.
enum SCANLINE_ORDER ScanlineOrder DEFAULT_INITIALIZER(SCANLINE_ORDER_UNSPECIFIED);
};
typedef struct FullScreenModeDesc FullScreenModeDesc;
/// Engine creation attibutes
struct EngineCreateInfo
{
/// API version number.
Int32 APIVersion DEFAULT_INITIALIZER(DILIGENT_API_VERSION);
/// Pointer to the raw memory allocator that will be used for all memory allocation/deallocation
/// operations in the engine
struct IMemoryAllocator* pRawMemAllocator DEFAULT_INITIALIZER(nullptr);
/// Pointer to the user-specified debug message callback function
DebugMessageCallbackType DebugMessageCallback DEFAULT_INITIALIZER(nullptr);
/// Number of deferred contexts to create when initializing the engine. If non-zero number
/// is given, pointers to the contexts are written to ppContexts array by the engine factory
/// functions (IEngineFactoryD3D11::CreateDeviceAndContextsD3D11,
/// IEngineFactoryD3D12::CreateDeviceAndContextsD3D12, and IEngineFactoryVk::CreateDeviceAndContextsVk)
/// starting at position 1.
Uint32 NumDeferredContexts DEFAULT_INITIALIZER(0);
};
typedef struct EngineCreateInfo EngineCreateInfo;
/// Attributes of the OpenGL-based engine implementation
struct EngineGLCreateInfo DILIGENT_DERIVE(EngineCreateInfo)
/// Native window wrapper
NativeWindow Window;
/// Create debug OpenGL context and enable debug output.
/// Debug contexts are intended for use during application development, and
/// provide additional runtime checking, validation, and logging
/// functionality while possibly incurring performance penalties
bool CreateDebugContext DEFAULT_INITIALIZER(false);
};
typedef struct EngineGLCreateInfo EngineGLCreateInfo;
/// Debug flags that can be specified when creating Direct3D11-based engine implementation.
///
/// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11
DILIGENT_TYPED_ENUM(D3D11_DEBUG_FLAGS, Uint32)
{
/// No debug flag
D3D11_DEBUG_FLAG_NONE = 0x00,
/// Whether to create Direct3D11 debug device
D3D11_DEBUG_FLAG_CREATE_DEBUG_DEVICE = 0x01,
/// Before executing draw/dispatch command, verify that
/// all required shader resources are bound to the device context
D3D11_DEBUG_FLAG_VERIFY_COMMITTED_SHADER_RESOURCES = 0x02,
/// Verify that all committed cotext resources are relevant,
/// i.e. they are consistent with the committed resource cache.
/// This is very expensive and should generally not be necessary.
D3D11_DEBUG_FLAG_VERIFY_COMMITTED_RESOURCE_RELEVANCE = 0x04
};
DEFINE_FLAG_ENUM_OPERATORS(D3D11_DEBUG_FLAGS)
/// Direct3D11/12 feature level
DILIGENT_TYPED_ENUM(DIRECT3D_FEATURE_LEVEL, Uint8)
{
/// Feature level 10.0
DIRECT3D_FEATURE_LEVEL_10_0,
/// Feature level 10.1
DIRECT3D_FEATURE_LEVEL_10_1,
/// Feature level 11.0
DIRECT3D_FEATURE_LEVEL_11_0,
/// Feature level 11.1
DIRECT3D_FEATURE_LEVEL_11_1,
/// Feature level 12.0
DIRECT3D_FEATURE_LEVEL_12_0,
/// Feature level 12.1
DIRECT3D_FEATURE_LEVEL_12_1
};
static const Uint32 DEFAULT_ADAPTER_ID = 0xFFFFFFFFU;
/// Attributes specific to D3D11 engine
struct EngineD3D11CreateInfo DILIGENT_DERIVE(EngineCreateInfo)
/// Id of the hardware adapter the engine should be initialized on.
Uint32 AdapterId DEFAULT_INITIALIZER(DEFAULT_ADAPTER_ID);
/// Minimum required Direct3D feature level.
DIRECT3D_FEATURE_LEVEL MinimumFeatureLevel DEFAULT_INITIALIZER(DIRECT3D_FEATURE_LEVEL_11_0);
/// Debug flags. See Diligent::D3D11_DEBUG_FLAGS for a list of allowed values.
///
/// \sa CreateDeviceAndContextsD3D11Type, CreateSwapChainD3D11Type, LoadGraphicsEngineD3D11
D3D11_DEBUG_FLAGS DebugFlags DEFAULT_INITIALIZER(D3D11_DEBUG_FLAG_NONE);
};
typedef struct EngineD3D11CreateInfo EngineD3D11CreateInfo;
/// Attributes specific to D3D12 engine
struct EngineD3D12CreateInfo DILIGENT_DERIVE(EngineCreateInfo)
/// Name of the D3D12 DLL to load. Ignored on UWP.
const char* D3D12DllName DEFAULT_INITIALIZER("d3d12.dll");
/// Id of the hardware adapter the engine should be initialized on.
Uint32 AdapterId DEFAULT_INITIALIZER(DEFAULT_ADAPTER_ID);
/// Minimum required Direct3D feature level.
DIRECT3D_FEATURE_LEVEL MinimumFeatureLevel DEFAULT_INITIALIZER(DIRECT3D_FEATURE_LEVEL_11_0);
/// Enable Direct3D12 debug layer.
bool EnableDebugLayer DEFAULT_INITIALIZER(false);
/// Enable validation on the GPU timeline.
/// See https://docs.microsoft.com/en-us/windows/win32/direct3d12/using-d3d12-debug-layer-gpu-based-validation
/// This flag only has effect if EnableDebugLayer is true.
/// \note Enabling this option may slow things down a lot.
bool EnableGPUBasedValidation DEFAULT_INITIALIZER(false);
/// Whether to break execution when D3D12 debug layer detects an error.
/// This flag only has effect if EnableDebugLayer is true.
bool BreakOnError DEFAULT_INITIALIZER(false);
/// Whether to break execution when D3D12 debug layer detects a memory corruption.
/// This flag only has effect if EnableDebugLayer is true.
bool BreakOnCorruption DEFAULT_INITIALIZER(true);
/// Size of the CPU descriptor heap allocations for different heap types.
Uint32 CPUDescriptorHeapAllocationSize[4]
#if DILIGENT_CPP_INTERFACE
{
8192, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
2048, // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
1024, // D3D12_DESCRIPTOR_HEAP_TYPE_RTV
1024 // D3D12_DESCRIPTOR_HEAP_TYPE_DSV
}
#endif
;
/// The size of the GPU descriptor heap region designated to static/mutable
/// shader resource variables.
/// Every Shader Resource Binding object allocates one descriptor
/// per any static/mutable shader resource variable (every array
/// element counts) when the object is created. All required descriptors
/// are allocated in one continuous chunk.
/// GPUDescriptorHeapSize defines the total number of all descriptors
/// that can be allocated across all SRB objects.
/// Note that due to heap fragmentation, releaseing two chunks of sizes
/// N and M does not necessarily make the chunk of size N+M available.
Uint32 GPUDescriptorHeapSize[2]
#if DILIGENT_CPP_INTERFACE
{
16384, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
1024 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
}
#endif
;
/// The size of the GPU descriptor heap region designated to dynamic
/// shader resource variables.
/// Every Shader Resource Binding object allocates one descriptor
/// per any dynamic shader resource variable (every array element counts)
/// every time the object is commited via IDeviceContext::CommitShaderResources.
/// All used dynamic descriptors are discarded at the end of the frame
/// and recycled when they are no longer used by the GPU.
/// GPUDescriptorHeapDynamicSize defines the total number of descriptors
/// that can be used for dynamic variables across all SRBs and all frames
/// currently in flight.
/// Note that in Direct3D12, the size of sampler descriptor heap is limited
/// by 2048. Since Diligent Engine allocates single heap for all variable types,
/// GPUDescriptorHeapSize[1] + GPUDescriptorHeapDynamicSize[1] must not
/// exceed 2048.
Uint32 GPUDescriptorHeapDynamicSize[2]
#if DILIGENT_CPP_INTERFACE
{
8192, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
1024 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
}
#endif
;
/// The size of the chunk that dynamic descriptor allocations manager
/// requests from the main GPU descriptor heap.
/// The total number of dynamic descriptors avaialble across all frames in flight is
/// defined by GPUDescriptorHeapDynamicSize. Every device context allocates dynamic
/// descriptors in two stages: it first requests a chunk from the global heap, and the
/// performs linear suballocations from this chunk in a lock-free manner. The size of
/// this chunk is defined by DynamicDescriptorAllocationChunkSize, thus there will be total
/// GPUDescriptorHeapDynamicSize/DynamicDescriptorAllocationChunkSize chunks in
/// the heap of each type.
Uint32 DynamicDescriptorAllocationChunkSize[2]
#if DILIGENT_CPP_INTERFACE
{
256, // D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
32 // D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
}
#endif
;
/// Number of commands to flush the command list. Only draw/dispatch commands count
/// towards the limit. Command lists are only flushed when pipeline state is changed
/// or when backbuffer is presented.
Uint32 NumCommandsToFlushCmdList DEFAULT_INITIALIZER(256);
/// A device context uses dynamic heap when it needs to allocate temporary
/// CPU-accessible memory to update a resource via IBufer::UpdateData() or
/// ITexture::UpdateData(), or to map dynamic resources.
/// Device contexts first request a chunk of memory from global dynamic
/// resource manager and then suballocate from this chunk in a lock-free
/// fashion. DynamicHeapPageSize defines the size of this chunk.
Uint32 DynamicHeapPageSize DEFAULT_INITIALIZER(1 << 20);
/// Number of dynamic heap pages that will be reserved by the
/// global dynamic heap manager to avoid page creation at run time.
Uint32 NumDynamicHeapPagesToReserve DEFAULT_INITIALIZER(1);
/// Query pool size for each query type.
Uint32 QueryPoolSizes[5]
#if DILIGENT_CPP_INTERFACE
{
0, // Ignored
128, // QUERY_TYPE_OCCLUSION
128, // QUERY_TYPE_BINARY_OCCLUSION
512, // QUERY_TYPE_TIMESTAMP
128 // QUERY_TYPE_PIPELINE_STATISTICS
}
#endif
;
};
typedef struct EngineD3D12CreateInfo EngineD3D12CreateInfo;
/// Descriptor pool size
struct VulkanDescriptorPoolSize
{
Uint32 MaxDescriptorSets DEFAULT_INITIALIZER(0);
Uint32 NumSeparateSamplerDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumCombinedSamplerDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumSampledImageDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumStorageImageDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumUniformBufferDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumStorageBufferDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumUniformTexelBufferDescriptors DEFAULT_INITIALIZER(0);
Uint32 NumStorageTexelBufferDescriptors DEFAULT_INITIALIZER(0);
#if DILIGENT_CPP_INTERFACE
VulkanDescriptorPoolSize()noexcept {}
VulkanDescriptorPoolSize(Uint32 _MaxDescriptorSets,
Uint32 _NumSeparateSamplerDescriptors,
Uint32 _NumCombinedSamplerDescriptors,
Uint32 _NumSampledImageDescriptors,
Uint32 _NumStorageImageDescriptors,
Uint32 _NumUniformBufferDescriptors,
Uint32 _NumStorageBufferDescriptors,
Uint32 _NumUniformTexelBufferDescriptors,
Uint32 _NumStorageTexelBufferDescriptors)noexcept :
MaxDescriptorSets {_MaxDescriptorSets },
NumSeparateSamplerDescriptors {_NumSeparateSamplerDescriptors },
NumCombinedSamplerDescriptors {_NumCombinedSamplerDescriptors },
NumSampledImageDescriptors {_NumSampledImageDescriptors },
NumStorageImageDescriptors {_NumStorageImageDescriptors },
NumUniformBufferDescriptors {_NumUniformBufferDescriptors },
NumStorageBufferDescriptors {_NumStorageBufferDescriptors },
NumUniformTexelBufferDescriptors{_NumUniformTexelBufferDescriptors},
NumStorageTexelBufferDescriptors{_NumStorageTexelBufferDescriptors}
{
// On clang aggregate initialization fails to compile if
// structure members have default initializers
}
#endif
};
typedef struct VulkanDescriptorPoolSize VulkanDescriptorPoolSize;
/// Attributes specific to Vulkan engine
struct EngineVkCreateInfo DILIGENT_DERIVE(EngineCreateInfo)
/// Enable Vulkan validation layers.
bool EnableValidation DEFAULT_INITIALIZER(false);
/// Number of global Vulkan extensions
Uint32 GlobalExtensionCount DEFAULT_INITIALIZER(0);
/// List of global Vulkan extensions to enable.
const char* const* ppGlobalExtensionNames DEFAULT_INITIALIZER(nullptr);
/// Allocator used as pAllocator parameter in callse to Vulkan Create* functions
void* pVkAllocator DEFAULT_INITIALIZER(nullptr);
/// Number of commands to flush the command buffer. Only draw/dispatch commands count
/// towards the limit. Command buffers are only flushed when pipeline state is changed
/// or when backbuffer is presented.
Uint32 NumCommandsToFlushCmdBuffer DEFAULT_INITIALIZER(256);
/// Size of the main descriptor pool that is used to allocate descriptor sets
/// for static and mutable variables. If allocation from the current pool fails,
/// the engine creates another one.
VulkanDescriptorPoolSize MainDescriptorPoolSize
#if DILIGENT_CPP_INTERFACE
//Max SepSm CmbSm SmpImg StrImg UB SB UTxB StTxB
{8192, 1024, 8192, 8192, 1024, 4096, 4096, 1024, 1024}
#endif
;
/// Size of the dynamic descriptor pool that is used to allocate descriptor sets
/// for dynamic variables. Every device context has its own dynamic descriptor set allocator.
/// The allocator requests pools from global dynamic descriptor pool manager, and then
/// performs lock-free suballocations from the pool.
VulkanDescriptorPoolSize DynamicDescriptorPoolSize
#if DILIGENT_CPP_INTERFACE
//Max SepSm CmbSm SmpImg StrImg UB SB UTxB StTxB
{2048, 256, 2048, 2048, 256, 1024, 1024, 256, 256}
#endif
;
/// Allocation granularity for device-local memory
Uint32 DeviceLocalMemoryPageSize DEFAULT_INITIALIZER(16 << 20);
/// Allocation granularity for host-visible memory
Uint32 HostVisibleMemoryPageSize DEFAULT_INITIALIZER(16 << 20);
/// Amount of device-local memory reserved by the engine.
/// The engine does not pre-allocate the memory, but rather keeps free
/// pages when resources are released
Uint32 DeviceLocalMemoryReserveSize DEFAULT_INITIALIZER(256 << 20);
/// Amount of host-visible memory reserved by the engine.
/// The engine does not pre-allocate the memory, but rather keeps free
/// pages when resources are released
Uint32 HostVisibleMemoryReserveSize DEFAULT_INITIALIZER(256 << 20);
/// Page size of the upload heap that is allocated by immediate/deferred
/// contexts from the global memory manager to perform lock-free dynamic
/// suballocations.
/// Upload heap is used to update resources with UpdateData()
Uint32 UploadHeapPageSize DEFAULT_INITIALIZER(1 << 20);
/// Size of the dynamic heap (the buffer that is used to suballocate
/// memory for dynamic resources) shared by all contexts.
Uint32 DynamicHeapSize DEFAULT_INITIALIZER(8 << 20);
/// Size of the memory chunk suballocated by immediate/deferred context from
/// the global dynamic heap to perform lock-free dynamic suballocations
Uint32 DynamicHeapPageSize DEFAULT_INITIALIZER(256 << 10);
/// Query pool size for each query type.
Uint32 QueryPoolSizes[5]
#if DILIGENT_CPP_INTERFACE
{
0, // Ignored
128, // QUERY_TYPE_OCCLUSION
128, // QUERY_TYPE_BINARY_OCCLUSION
512, // QUERY_TYPE_TIMESTAMP
128 // QUERY_TYPE_PIPELINE_STATISTICS
}
#endif
;
};
typedef struct EngineVkCreateInfo EngineVkCreateInfo;
/// Attributes of the Metal-based engine implementation
struct EngineMtlCreateInfo DILIGENT_DERIVE(EngineCreateInfo)
};
typedef struct EngineMtlCreateInfo EngineMtlCreateInfo;
/// Box
struct Box
{
Uint32 MinX DEFAULT_INITIALIZER(0); ///< Minimal X coordinate. Default value is 0
Uint32 MaxX DEFAULT_INITIALIZER(0); ///< Maximal X coordinate. Default value is 0
Uint32 MinY DEFAULT_INITIALIZER(0); ///< Minimal Y coordinate. Default value is 0
Uint32 MaxY DEFAULT_INITIALIZER(0); ///< Maximal Y coordinate. Default value is 0
Uint32 MinZ DEFAULT_INITIALIZER(0); ///< Minimal Z coordinate. Default value is 0
Uint32 MaxZ DEFAULT_INITIALIZER(1); ///< Maximal Z coordinate. Default value is 1
#if DILIGENT_CPP_INTERFACE
Box(Uint32 _MinX, Uint32 _MaxX,
Uint32 _MinY, Uint32 _MaxY,
Uint32 _MinZ, Uint32 _MaxZ) noexcept:
MinX {_MinX},
MaxX {_MaxX},
MinY {_MinY},
MaxY {_MaxY},
MinZ {_MinZ},
MaxZ {_MaxZ}
{}
Box(Uint32 _MinX, Uint32 _MaxX,
Uint32 _MinY, Uint32 _MaxY) noexcept:
Box{_MinX, _MaxX, _MinY, _MaxY, 0, 1}
{}
Box(Uint32 _MinX, Uint32 _MaxX) noexcept:
Box{_MinX, _MaxX, 0, 0, 0, 1}
{}
Box() noexcept {}
#endif
};
typedef struct Box Box;
/// Describes texture format component type
DILIGENT_TYPED_ENUM(COMPONENT_TYPE, Uint8)
{
/// Undefined component type
COMPONENT_TYPE_UNDEFINED,
/// Floating point component type
COMPONENT_TYPE_FLOAT,
/// Signed-normalized-integer component type
COMPONENT_TYPE_SNORM,
/// Unsigned-normalized-integer component type
COMPONENT_TYPE_UNORM,
/// Unsigned-normalized-integer sRGB component type
COMPONENT_TYPE_UNORM_SRGB,
/// Signed-integer component type
COMPONENT_TYPE_SINT,
/// Unsigned-integer component type
COMPONENT_TYPE_UINT,
/// Depth component type
COMPONENT_TYPE_DEPTH,
/// Depth-stencil component type
COMPONENT_TYPE_DEPTH_STENCIL,
/// Compound component type (example texture formats: TEX_FORMAT_R11G11B10_FLOAT or TEX_FORMAT_RGB9E5_SHAREDEXP)
COMPONENT_TYPE_COMPOUND,
/// Compressed component type
COMPONENT_TYPE_COMPRESSED,
};
/// Describes invariant texture format attributes. These attributes are
/// intrinsic to the texture format itself and do not depend on the
/// format support.
struct TextureFormatAttribs
{
/// Literal texture format name (for instance, for TEX_FORMAT_RGBA8_UNORM format, this
/// will be "TEX_FORMAT_RGBA8_UNORM")
const Char* Name DEFAULT_INITIALIZER("TEX_FORMAT_UNKNOWN");
/// Texture format, see Diligent::TEXTURE_FORMAT for a list of supported texture formats
TEXTURE_FORMAT Format DEFAULT_INITIALIZER(TEX_FORMAT_UNKNOWN);
/// Size of one component in bytes (for instance, for TEX_FORMAT_RGBA8_UNORM format, this will be 1)
/// For compressed formats, this is the block size in bytes (for TEX_FORMAT_BC1_UNORM format, this will be 8)
Uint8 ComponentSize DEFAULT_INITIALIZER(0);
/// Number of components
Uint8 NumComponents DEFAULT_INITIALIZER(0);
/// Component type, see Diligent::COMPONENT_TYPE for details.
COMPONENT_TYPE ComponentType DEFAULT_INITIALIZER(COMPONENT_TYPE_UNDEFINED);
/// Bool flag indicating if the format is a typeless format
bool IsTypeless DEFAULT_INITIALIZER(false);
/// For block-compressed formats, compression block width
Uint8 BlockWidth DEFAULT_INITIALIZER(0);
/// For block-compressed formats, compression block height
Uint8 BlockHeight DEFAULT_INITIALIZER(0);
#if DILIGENT_CPP_INTERFACE
/// For non-compressed formats, returns the texel size.
/// For block-compressed formats, returns the block size.
Uint32 GetElementSize() const
{
return Uint32{ComponentSize} * (ComponentType != COMPONENT_TYPE_COMPRESSED ? Uint32{NumComponents} : Uint32{1});
}
/// Initializes the structure
TextureFormatAttribs( const Char* _Name,
TEXTURE_FORMAT _Format,
Uint8 _ComponentSize,
Uint8 _NumComponents,
COMPONENT_TYPE _ComponentType,
bool _IsTypeless,
Uint8 _BlockWidth,
Uint8 _BlockHeight)noexcept :
Name {_Name },
Format {_Format },
ComponentSize{_ComponentSize},
NumComponents{_NumComponents},
ComponentType{_ComponentType},
IsTypeless {_IsTypeless },
BlockWidth {_BlockWidth },
BlockHeight {_BlockHeight }
{
}
TextureFormatAttribs()noexcept {}
#endif
};
typedef struct TextureFormatAttribs TextureFormatAttribs;
/// Basic texture format description
/// This structure is returned by IRenderDevice::GetTextureFormatInfo()
struct TextureFormatInfo DILIGENT_DERIVE(TextureFormatAttribs)
/// Indicates if the format is supported by the device
bool Supported DEFAULT_INITIALIZER(false);
};
typedef struct TextureFormatInfo TextureFormatInfo;
/// Extended texture format description
/// This structure is returned by IRenderDevice::GetTextureFormatInfoExt()
struct TextureFormatInfoExt DILIGENT_DERIVE(TextureFormatInfo)
/// Indicates if the format can be filtered
bool Filterable DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used as a render target format
bool ColorRenderable DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used as a depth format
bool DepthRenderable DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used to create a 1D texture
bool Tex1DFmt DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used to create a 2D texture
bool Tex2DFmt DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used to create a 3D texture
bool Tex3DFmt DEFAULT_INITIALIZER(false);
/// Indicates if the format can be used to create a cube texture
bool TexCubeFmt DEFAULT_INITIALIZER(false);
/// A bitmask specifying all the supported sample counts for this texture format.
/// If the format supports n samples, then (SampleCounts & n) != 0
Uint32 SampleCounts DEFAULT_INITIALIZER(0);
};
typedef struct TextureFormatInfoExt TextureFormatInfoExt;
/// Resource usage state
DILIGENT_TYPED_ENUM(RESOURCE_STATE, Uint32)
{
/// The resource state is not known to the engine and is managed by the application
RESOURCE_STATE_UNKNOWN = 0x0000,
/// The resource state is known to the engine, but is undefined. A resource is typically in an undefined state right after initialization.
RESOURCE_STATE_UNDEFINED = 0x0001,
/// The resource is accessed as vertex buffer
RESOURCE_STATE_VERTEX_BUFFER = 0x0002,
/// The resource is accessed as constant (uniform) buffer
RESOURCE_STATE_CONSTANT_BUFFER = 0x0004,
/// The resource is accessed as index buffer
RESOURCE_STATE_INDEX_BUFFER = 0x0008,
/// The resource is accessed as render target
RESOURCE_STATE_RENDER_TARGET = 0x0010,
/// The resource is used for unordered access
RESOURCE_STATE_UNORDERED_ACCESS = 0x0020,
/// The resource is used in a writable depth-stencil view or in clear operation
RESOURCE_STATE_DEPTH_WRITE = 0x0040,
/// The resource is used in a read-only depth-stencil view
RESOURCE_STATE_DEPTH_READ = 0x0080,
/// The resource is accessed from a shader
RESOURCE_STATE_SHADER_RESOURCE = 0x0100,
/// The resource is used as the destination for stream output
RESOURCE_STATE_STREAM_OUT = 0x0200,
/// The resource is used as indirect draw/dispatch arguments buffer
RESOURCE_STATE_INDIRECT_ARGUMENT = 0x0400,
/// The resource is used as the destination in a copy operation
RESOURCE_STATE_COPY_DEST = 0x0800,
/// The resource is used as the source in a copy operation
RESOURCE_STATE_COPY_SOURCE = 0x1000,
/// The resource is used as the destination in a resolve operation
RESOURCE_STATE_RESOLVE_DEST = 0x2000,
/// The resource is used as the source in a resolve operation
RESOURCE_STATE_RESOLVE_SOURCE = 0x4000,
/// The resource is used for present
RESOURCE_STATE_PRESENT = 0x8000,
RESOURCE_STATE_MAX_BIT = 0x8000,
RESOURCE_STATE_GENERIC_READ = RESOURCE_STATE_VERTEX_BUFFER |
RESOURCE_STATE_CONSTANT_BUFFER |
RESOURCE_STATE_INDEX_BUFFER |
RESOURCE_STATE_SHADER_RESOURCE |
RESOURCE_STATE_INDIRECT_ARGUMENT |
RESOURCE_STATE_COPY_SOURCE
};
/// State transition barrier type
DILIGENT_TYPED_ENUM(STATE_TRANSITION_TYPE, Uint8)
{
/// Perform state transition immediately.
STATE_TRANSITION_TYPE_IMMEDIATE = 0,
/// Begin split barrier. This mode only has effect in Direct3D12 backend, and corresponds to
/// [D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY](https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ne-d3d12-d3d12_resource_barrier_flags)
/// flag. See https://docs.microsoft.com/en-us/windows/desktop/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12#split-barriers.
/// In other backends, begin-split barriers are ignored.
STATE_TRANSITION_TYPE_BEGIN,
/// End split barrier. This mode only has effect in Direct3D12 backend, and corresponds to
/// [D3D12_RESOURCE_BARRIER_FLAG_END_ONLY](https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ne-d3d12-d3d12_resource_barrier_flags)
/// flag. See https://docs.microsoft.com/en-us/windows/desktop/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12#split-barriers.
/// In other backends, this mode is similar to STATE_TRANSITION_TYPE_IMMEDIATE.
STATE_TRANSITION_TYPE_END
};
static const Uint32 REMAINING_MIP_LEVELS = 0xFFFFFFFFU;
static const Uint32 REMAINING_ARRAY_SLICES = 0xFFFFFFFFU;
/// Resource state transition barrier description
struct StateTransitionDesc
{
/// Texture to transition.
/// \note Exactly one of pTexture or pBuffer must be non-null.
struct ITexture* pTexture DEFAULT_INITIALIZER(nullptr);
/// Buffer to transition.
/// \note Exactly one of pTexture or pBuffer must be non-null.
struct IBuffer* pBuffer DEFAULT_INITIALIZER(nullptr);
/// When transitioning a texture, first mip level of the subresource range to transition.
Uint32 FirstMipLevel DEFAULT_INITIALIZER(0);
/// When transitioning a texture, number of mip levels of the subresource range to transition.
Uint32 MipLevelsCount DEFAULT_INITIALIZER(REMAINING_MIP_LEVELS);
/// When transitioning a texture, first array slice of the subresource range to transition.
Uint32 FirstArraySlice DEFAULT_INITIALIZER(0);
/// When transitioning a texture, number of array slices of the subresource range to transition.
Uint32 ArraySliceCount DEFAULT_INITIALIZER(REMAINING_ARRAY_SLICES);
/// Resource state before transition. If this value is RESOURCE_STATE_UNKNOWN,
/// internal resource state will be used, which must be defined in this case.
RESOURCE_STATE OldState DEFAULT_INITIALIZER(RESOURCE_STATE_UNKNOWN);
/// Resource state after transition.
RESOURCE_STATE NewState DEFAULT_INITIALIZER(RESOURCE_STATE_UNKNOWN);
/// State transition type, see Diligent::STATE_TRANSITION_TYPE.
/// \note When issuing UAV barrier (i.e. OldState and NewState equal RESOURCE_STATE_UNORDERED_ACCESS),
/// TransitionType must be STATE_TRANSITION_TYPE_IMMEDIATE.
STATE_TRANSITION_TYPE TransitionType DEFAULT_INITIALIZER(STATE_TRANSITION_TYPE_IMMEDIATE);
/// If set to true, the internal resource state will be set to NewState and the engine
/// will be able to take over the resource state management. In this case it is the
/// responsibility of the application to make sure that all subresources are indeed in
/// designated state.
/// If set to false, internal resource state will be unchanged.
/// \note When TransitionType is STATE_TRANSITION_TYPE_BEGIN, this member must be false.
bool UpdateResourceState DEFAULT_INITIALIZER(false);
#if DILIGENT_CPP_INTERFACE
StateTransitionDesc()noexcept{}
StateTransitionDesc(ITexture* _pTexture,
RESOURCE_STATE _OldState,
RESOURCE_STATE _NewState,
Uint32 _FirstMipLevel = 0,
Uint32 _MipLevelsCount = REMAINING_MIP_LEVELS,
Uint32 _FirstArraySlice = 0,
Uint32 _ArraySliceCount = REMAINING_ARRAY_SLICES,
STATE_TRANSITION_TYPE _TransitionType = STATE_TRANSITION_TYPE_IMMEDIATE,
bool _UpdateState = false)noexcept :
pTexture {_pTexture },
FirstMipLevel {_FirstMipLevel },
MipLevelsCount {_MipLevelsCount },
FirstArraySlice {_FirstArraySlice},
ArraySliceCount {_ArraySliceCount},
OldState {_OldState },
NewState {_NewState },
TransitionType {_TransitionType },
UpdateResourceState {_UpdateState }
{}
StateTransitionDesc(ITexture* _pTexture,
RESOURCE_STATE _OldState,
RESOURCE_STATE _NewState,
bool _UpdateState)noexcept :
StateTransitionDesc
{
_pTexture,
_OldState,
_NewState,
0,
REMAINING_MIP_LEVELS,
0,
REMAINING_ARRAY_SLICES,
STATE_TRANSITION_TYPE_IMMEDIATE,
_UpdateState
}
{}
StateTransitionDesc(IBuffer* _pBuffer,
RESOURCE_STATE _OldState,
RESOURCE_STATE _NewState,
bool _UpdateState)noexcept :
pBuffer {_pBuffer },
OldState {_OldState },
NewState {_NewState },
UpdateResourceState {_UpdateState}
{}
#endif
};
typedef struct StateTransitionDesc StateTransitionDesc;
DILIGENT_END_NAMESPACE // namespace Diligent
| 49.849833 | 173 | 0.724663 | [
"render",
"object",
"transform",
"3d"
] |
ecd32ab4fca9018843a8304b36d4e89ba4ba2c46 | 7,872 | h | C | Core/CLI/src/cli_Aliases.h | emamanto/Soar | 72d2bc095068dd87ac78dad4f48938f6edc0353a | [
"BSD-2-Clause"
] | 2 | 2019-11-21T14:40:00.000Z | 2020-10-25T15:44:53.000Z | Core/CLI/src/cli_Aliases.h | emamanto/Soar | 72d2bc095068dd87ac78dad4f48938f6edc0353a | [
"BSD-2-Clause"
] | null | null | null | Core/CLI/src/cli_Aliases.h | emamanto/Soar | 72d2bc095068dd87ac78dad4f48938f6edc0353a | [
"BSD-2-Clause"
] | 2 | 2019-12-23T05:06:28.000Z | 2020-01-16T12:57:55.000Z | #ifndef CLI_ALIASES_H
#define CLI_ALIASES_H
#include <string>
#include <map>
#include <vector>
#include <iterator>
#include "tokenizer.h"
namespace cli
{
class Aliases : public soar::tokenizer_callback
{
public:
Aliases()
{
// defaults
soar::tokenizer t;
t.set_handler(this);
// Traditional Soar aliases
t.evaluate("? help");
t.evaluate("a alias");
t.evaluate("aw wm add");
t.evaluate("chdir cd");
t.evaluate("ctf output command-to-file");
t.evaluate("d run -d");
t.evaluate("dir ls");
t.evaluate("e run -e");
t.evaluate("ex production excise");
t.evaluate("fc production firing-counts");
t.evaluate("gds_print print --gds");
t.evaluate("inds decide indifferent-selection");
t.evaluate("init soar init");
t.evaluate("interrupt soar stop");
t.evaluate("is soar init");
t.evaluate("man help");
t.evaluate("p print");
t.evaluate("pc print --chunks");
t.evaluate("ps print --stack");
t.evaluate("pw production watch");
t.evaluate("quit exit");
t.evaluate("r run");
t.evaluate("rn load rete-network");
t.evaluate("rw wm remove");
t.evaluate("s run 1");
t.evaluate("set-default-depth output print-depth");
t.evaluate("ss soar stop");
t.evaluate("st stats");
t.evaluate("step run -d");
t.evaluate("stop soar stop");
t.evaluate("topd pwd");
t.evaluate("un alias -r");
t.evaluate("varprint print -v -d 100");
t.evaluate("w trace");
t.evaluate("wmes print -depth 0 -internal");
// New chunking and explain aliases
t.evaluate("cs chunk stats");
t.evaluate("c explain chunk");
t.evaluate("ef explain formation");
t.evaluate("ei explain identities");
t.evaluate("es explain stats");
t.evaluate("i explain instantiation");
t.evaluate("wt explain wm-trace");
t.evaluate("et explain explanation-trace");
// Backward compatibility aliases
t.evaluate("unalias alias -r");
t.evaluate("indifferent-selection decide indifferent-selection");
t.evaluate("numeric-indifferent-mode decide numeric-indifferent-mode");
t.evaluate("predict decide predict");
t.evaluate("select decide select");
t.evaluate("srand decide srand");
t.evaluate("replay-input load percepts");
t.evaluate("rete-net load rete-network");
t.evaluate("load-library load library");
t.evaluate("source load file");
t.evaluate("capture-input save percepts");
t.evaluate("pbreak production break");
t.evaluate("excise production excise");
t.evaluate("production-find production find");
t.evaluate("firing-counts production firing-counts");
t.evaluate("matches production matches");
t.evaluate("memories production memory-usage");
t.evaluate("multi-attributes production optimize-attribute");
t.evaluate("pwatch production watch");
t.evaluate("add-wme wm add");
t.evaluate("wma wm activation");
t.evaluate("remove-wme wm remove");
t.evaluate("watch-wmes wm watch");
t.evaluate("allocate debug allocate");
t.evaluate("internal-symbols debug internal-symbols");
t.evaluate("port debug port");
t.evaluate("time debug time");
t.evaluate("init-soar soar init");
t.evaluate("stop-soar soar stop");
t.evaluate("gp-max soar max-gp");
t.evaluate("max-dc-time soar max-dc-time");
t.evaluate("max-elaborations soar max-elaborations");
t.evaluate("max-goal-depth soar max-goal-depth");
t.evaluate("max-memory-usage soar max-memory-usage");
t.evaluate("max-nil-output-cycles soar max-nil-output-cycles");
t.evaluate("set-stop-phase soar stop-phase");
t.evaluate("soarnews soar");
t.evaluate("cli soar tcl");
t.evaluate("tcl soar tcl");
t.evaluate("timers soar timers");
t.evaluate("version soar version");
t.evaluate("waitsnc soar wait-snc");
t.evaluate("chunk-name-format chunk naming-style");
t.evaluate("max-chunks chunk max-chunks");
t.evaluate("clog output log");
t.evaluate("command-to-file output command-to-file");
t.evaluate("default-wme-depth output print-depth");
t.evaluate("echo-commands output echo-commands");
t.evaluate("verbose trace -A");
t.evaluate("warnings output warnings");
t.evaluate("watch trace");
}
virtual ~Aliases() {}
virtual bool handle_command(std::vector< std::string >& argv)
{
SetAlias(argv);
return true;
}
void SetAlias(const std::vector< std::string >& argv)
{
if (argv.empty())
{
return;
}
std::vector<std::string>::const_iterator i = argv.begin();
if (argv.size() == 1)
{
aliases.erase(*i);
}
else
{
std::vector<std::string>& cmd = aliases[*(i++)];
cmd.clear();
std::copy(i, argv.end(), std::back_inserter(cmd));
}
}
bool Expand(std::vector<std::string>& argv)
{
if (argv.empty())
{
return false;
}
std::map< std::string, std::vector< std::string > >::iterator iter = aliases.find(argv.front());
if (iter == aliases.end())
{
return false;
}
// overwrite first argument in argv
std::vector< std::string >::iterator insertion = argv.begin();
insertion->assign(iter->second[0]);
// insert any remaining args after that one
for (unsigned int i = 1; i < iter->second.size(); ++i)
{
++insertion;
insertion = argv.insert(insertion, iter->second[i]);
}
return true;
}
std::map< std::string, std::vector< std::string > >::const_iterator Begin()
{
return aliases.begin();
}
std::map< std::string, std::vector< std::string > >::const_iterator End()
{
return aliases.end();
}
private:
std::map< std::string, std::vector< std::string > > aliases;
};
} // namespace cli
#endif // CLI_ALIASES_H
| 38.4 | 112 | 0.469512 | [
"vector"
] |
ecd3aaf21fd8fd2cc3d4f4bb67b79cabf1131c99 | 8,034 | h | C | zircon/system/ulib/zxtest/include/zxtest/base/values.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | zircon/system/ulib/zxtest/include/zxtest/base/values.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 1 | 2022-03-01T01:12:04.000Z | 2022-03-01T01:17:26.000Z | zircon/system/ulib/zxtest/include/zxtest/base/values.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ZXTEST_BASE_VALUES_H_
#define ZXTEST_BASE_VALUES_H_
#include <lib/fit/function.h>
#include <lib/stdcompat/array.h>
#include <lib/stdcompat/span.h>
#include <math.h>
#include <optional>
#include <tuple>
#include <type_traits>
#include <vector>
#include <zxtest/base/test.h>
namespace zxtest {
namespace internal {
// This class takes provides a container interface but is based on taking a lambda that owns the
// storage of the parameters and provides access to them. The contained parameters are immutable.
template <typename T>
class ValueProvider {
public:
using ValueType = std::remove_cv_t<T>;
using ConstRef = const ValueType&;
using Callback = typename fit::function<ConstRef(size_t)>;
ValueProvider() = delete;
ValueProvider(Callback accessor, size_t size) : accessor_(std::move(accessor)), size_(size) {}
template <typename U,
std::enable_if_t<(std::is_convertible_v<U, T> || std::is_constructible_v<T, U>)>>
explicit ValueProvider(ValueProvider<U>&& provider)
: size_(provider.size()),
accessor_([provider = std::move(provider)](size_t i) -> const T& { return provider[i]; }) {}
ValueProvider(const ValueProvider&) = delete;
ValueProvider(ValueProvider&&) noexcept = default;
template <typename U, typename std::enable_if_t<
(std::is_convertible_v<U, T> ||
std::is_constructible_v<T, U>)&&!std::is_same_v<U, T>>* = nullptr>
ValueProvider(ValueProvider<U>&& other)
: accessor_([cb = std::move(other.accessor_)](size_t index) -> const T& {
static std::optional<cpp20::remove_cvref_t<T>> tmp;
tmp.emplace(cb(index));
return tmp.value();
}),
size_(other.size_) {}
ValueProvider& operator=(ValueProvider&&) noexcept = default;
~ValueProvider() = default;
ConstRef operator[](size_t index) const {
ZX_ASSERT_MSG(index < size_, "Out of range.");
return accessor_(index);
}
size_t size() const { return size_; }
private:
template <typename U>
friend class ValueProvider;
Callback accessor_ = nullptr;
size_t size_ = 0;
};
} // namespace internal
namespace internal {
// NOTE about `Combine`:
// We handle more than two parameters through recursion. The leftmost two parameters are combined
// into a tuple at each recursive call, and the tuples are merged using `std::tuple_cat`. However,
// if the user wants to pass in a tuple parameter, that must be handled like a regular value and not
// be concatenated using `std::tuple_cat`. The combination of `Combine` and `internal::Combine`
// functions handle this distinction.
// Internal combine handler.
// See above for a note about why there are internal handlers.
template <typename... A, typename B>
auto Combine(::zxtest::internal::ValueProvider<std::tuple<A...>> a,
::zxtest::internal::ValueProvider<B> b) {
using ParamType = decltype(std::tuple_cat(a[0], std::tuple(b[0])));
size_t total_elements = a.size() * b.size();
auto values = [a = std::move(a), b = std::move(b)](size_t index) -> ParamType& {
size_t a_index = index / b.size();
size_t b_index = index % b.size();
static ParamType storage;
storage = std::tuple_cat(a[a_index], std::tuple(b[b_index]));
return storage;
};
return ::zxtest::internal::ValueProvider<ParamType>(
[a = std::move(values)](size_t index) -> const ParamType& { return a(index); },
total_elements);
}
// Internal combine handler.
// See above for a note about why there are internal handlers.
template <typename... A, typename... B>
auto Combine(::zxtest::internal::ValueProvider<std::tuple<A...>> a,
::zxtest::internal::ValueProvider<std::tuple<B...>> b) {
using ParamType = decltype(std::tuple_cat(a[0], std::make_tuple(b[0])));
size_t total_elements = a.size() * b.size();
auto values = [a = std::move(a), b = std::move(b)](size_t index) -> ParamType& {
size_t a_index = index / b.size();
size_t b_index = index % b.size();
static ParamType storage;
storage = std::tuple_cat(a[a_index], std::make_tuple(b[b_index]));
return storage;
};
return ::zxtest::internal::ValueProvider<ParamType>(
[a = std::move(values)](size_t index) -> const ParamType& { return a(index); },
total_elements);
}
// Internal combine handler.
// See above for a note about why there are internal handlers.
template <typename A, typename B, typename... ProviderType>
auto Combine(::zxtest::internal::ValueProvider<A> a, ::zxtest::internal::ValueProvider<B> b,
ProviderType&&... providers) {
return internal::Combine(std::move(internal::Combine(std::move(a), std::move(b))),
std::forward<ProviderType>(providers)...);
}
} // namespace internal
// Combines two ValueProviders producing a ValueProvider with a cartesian product of both.
template <typename A, typename B>
auto Combine(::zxtest::internal::ValueProvider<A> a, ::zxtest::internal::ValueProvider<B> b) {
using ParamType = typename std::tuple<A, B>;
size_t total_elements = a.size() * b.size();
auto values = [a = std::move(a), b = std::move(b)](size_t index) -> ParamType& {
size_t a_index = index / b.size();
size_t b_index = index % b.size();
static ParamType storage;
storage = std::tuple(a[a_index], b[b_index]);
return storage;
};
return ::zxtest::internal::ValueProvider<ParamType>(
[a = std::move(values)](size_t index) -> const ParamType& { return a(index); },
total_elements);
}
// Combines more than two ValueProviders.
template <typename A, typename B, typename... ProviderType>
auto Combine(::zxtest::internal::ValueProvider<A> a, ::zxtest::internal::ValueProvider<B> b,
ProviderType&&... providers) {
return internal::Combine(std::move(zxtest::Combine(std::move(a), std::move(b))),
std::forward<ProviderType>(providers)...);
}
// Takes in a container of values and returns a ValueProvider for those values.
// Supports containers that support ::value_type and iterator.
template <typename C>
auto ValuesIn(const C& values) {
using ParamType = typename C::value_type;
size_t size = values.size();
return ::zxtest::internal::ValueProvider<ParamType>(
[values = std::move(values)](size_t index) -> const ParamType& {
return *(values.begin() + index);
},
size);
}
// Takes in values as parameters and returns a ValueProvider for those values.
template <typename... Args>
auto Values(Args... args) {
using ParamType = typename std::common_type<Args...>::type;
auto values = cpp20::to_array<ParamType>({args...});
return ValuesIn(values);
}
// Generates a series of values according to the parameters given.
// Increments by `step` starting from `start`, ending before `end`.
// The `end` value is excluded.
template <typename A, typename B, typename T>
auto Range(A start, B end, T step) {
static_assert((std::is_same_v<A, B>), "`start` and `end` parameters must be of equal type.");
ZX_ASSERT_MSG(start < end, "`start` must be less than `end`.");
A gap = end - start;
size_t size = static_cast<size_t>(ceil(static_cast<double>(gap) / static_cast<double>(step)));
return ::zxtest::internal::ValueProvider<A>(
[start = std::move(start), step = std::move(step)](size_t index) -> const A& {
static A result;
// Cast to `A` is safe because `index` is already enforced to be smaller than `size` in the
// `ValueProvider`.
result = start + (step * static_cast<A>(index));
return result;
},
size);
}
template <typename A, typename B>
auto Range(A start, B end) {
return Range(start, end, 1);
}
// Helper function to return a ValueProvider that has both bool values.
static inline auto Bool() { return Values(false, true); }
} // namespace zxtest
#endif // ZXTEST_BASE_VALUES_H_
| 38.811594 | 100 | 0.674259 | [
"vector"
] |
ecda5209290ec65470e7da1de0b8004eb0aa1ed2 | 40,314 | h | C | ZenGin/Gothic_II_Classic/API/zModel.h | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | null | null | null | ZenGin/Gothic_II_Classic/API/zModel.h | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | null | null | null | ZenGin/Gothic_II_Classic/API/zModel.h | ThielHater/nyx-core | ebff02a548f8ca31d6000c69b0482c99a840c991 | [
"MIT"
] | 1 | 2022-01-26T20:28:39.000Z | 2022-01-26T20:28:39.000Z | // Supported with union (c) 2018 Union team
#ifndef __ZMODEL_H__VER2__
#define __ZMODEL_H__VER2__
#include "zProgMesh.h"
namespace Gothic_II_Classic {
const float zMDL_ANI_BLEND_IN_ZERO = float_MAX;
const float zMDL_ANI_BLEND_OUT_ZERO =-float_MAX;
const int zMDL_ANIEVENT_MAXSTRING = 4;
const int zMAN_VERS = 12;
const int zMDL_MAX_ANIS_PARALLEL = 6;
const int zMDL_MAX_MESHLIBS_PARALLEL = 4;
const int zMDL_VELRING_SIZE = 8;
const int MAX_ANIHISTORY = 16;
enum zTMdl_AniDir {
zMDL_ANIDIR_FORWARD,
zMDL_ANIDIR_REVERSE,
zMDL_ANIDIR_ENDFASTEST
};
enum zTMdl_AniEventType {
zMDL_EVENT_TAG,
zMDL_EVENT_SOUND,
zMDL_EVENT_SOUND_GRND,
zMDL_EVENT_ANIBATCH,
zMDL_EVENT_SWAPMESH,
zMDL_EVENT_HEADING,
zMDL_EVENT_PFX,
zMDL_EVENT_PFX_GRND,
zMDL_EVENT_PFX_STOP,
zMDL_EVENT_SETMESH,
zMDL_EVENT_MM_STARTANI,
zMDL_EVENT_CAM_TREMOR
};
enum zTMdl_AniType {
zMDL_ANI_TYPE_NORMAL,
zMDL_ANI_TYPE_BLEND,
zMDL_ANI_TYPE_SYNC,
zMDL_ANI_TYPE_ALIAS,
zMDL_ANI_TYPE_BATCH,
zMDL_ANI_TYPE_COMB,
zMDL_ANI_TYPE_DISABLED
};
enum zTModelProtoImportMAXFlags {
zMDL_MAX_IMPORT_ANI = 1,
zMDL_MAX_IMPORT_MESH = 2,
zMDL_MAX_IMPORT_TREE = 4,
zMDL_MAX_IMPORT_PASS_ZCMESH = 8,
zMDL_MAX_IMPORT_NO_LOD = 16
};
class zCModelMeshLib : public zCObject {
public:
zCLASS_DECLARATION( zCModelMeshLib )
struct zTNodeMesh {
public:
zCVisual* visual;
int nodeIndex;
};
zCArray<zTNodeMesh> meshNodeList;
zCArray<zCMeshSoftSkin*> meshSoftSkinList;
void zCModelMeshLib_OnInit() zCall( 0x0058E5D0 );
zCModelMeshLib() zInit( zCModelMeshLib_OnInit() );
void ReleaseData() zCall( 0x00599B30 );
void AllocNumNodeVisuals( int ) zCall( 0x00599BA0 );
void AddMeshSoftSkin( zCMeshSoftSkin* ) zCall( 0x00599C10 );
void AddNodeVisual( int, zCVisual* ) zCall( 0x00599CF0 );
void ApplyToModel( zCModel* ) zCall( 0x00599DF0 );
void ApplyToModel( zCModelPrototype* ) zCall( 0x00599F60 );
void RemoveFromModel( zCModel* ) zCall( 0x0059A0C0 );
void BuildFromModel( zCModelPrototype* ) zCall( 0x0059A1B0 );
void BuildFromModel( zCModel* ) zCall( 0x0059A3A0 );
void SaveMDM( zCModelPrototype* ) zCall( 0x0059A5D0 );
void SaveMDM( zCFileBIN&, zCModelPrototype* ) zCall( 0x0059A7E0 );
static zCObject* _CreateNewInstance() zCall( 0x0057F310 );
static unsigned long GetMDMFileVersion() zCall( 0x0059A5A0 );
static int LoadMDM( zSTRING const&, zCModelPrototype*, zCModel*, zCModelMeshLib** ) zCall( 0x0059AC70 );
static int LoadMDM_Try( zSTRING const&, zCModelPrototype*, zCModel*, zCModelMeshLib** ) zCall( 0x0059B040 );
static int LoadMDM( zCFileBIN&, zCModelPrototype*, zCModel*, zCModelMeshLib** ) zCall( 0x0059B240 );
static int ConvertMDM( zSTRING const&, zCModelPrototype* ) zCall( 0x0059BD80 );
virtual zCClassDef* _GetClassDef() const zCall( 0x00579510 );
virtual ~zCModelMeshLib() zCall( 0x00599A60 );
};
class zCModelAniEvent {
public:
zTMdl_AniEventType aniEventType;
int frameNr;
zSTRING tagString;
zSTRING string[zMDL_ANIEVENT_MAXSTRING];
float value1;
float value2;
float value3;
float value4;
zCArray<zCSoundFX*> soundList;
zCArray<zCParticleEmitter*> pfxEmitterList;
void zCModelAniEvent_OnInit() zCall( 0x00582D20 );
zCModelAniEvent() zInit( zCModelAniEvent_OnInit() );
~zCModelAniEvent() zCall( 0x00582DC0 );
void Save( zCFileBIN& ) const zCall( 0x00582EA0 );
void Load( zCFileBIN& ) zCall( 0x00583000 );
};
class zCModelNode {
public:
zCModelNode* parentNode;
zSTRING nodeName;
zCVisual* visual;
zMAT4 trafo;
zVEC3 nodeRotAxis;
float nodeRotAngle;
zVEC3 translation;
zMAT4 trafoObjToWorld;
zMAT4* nodeTrafoList;
zCModelNodeInst* lastInstNode;
void zCModelNode_OnInit() zCall( 0x0057F460 );
void zCModelNode_OnInit( zCModelNode const& ) zCall( 0x0057F5A0 );
zCModelNode() zInit( zCModelNode_OnInit() );
zCModelNode( zCModelNode const& a0 ) zInit( zCModelNode_OnInit( a0 ));
~zCModelNode() zCall( 0x0057F730 );
void SetNodeVisualS( zCVisual* ) zCall( 0x0057F7D0 );
};
#pragma pack( push, 1 )
struct zTMdl_AniSample {
public:
unsigned short rotation[3];
unsigned short position[3];
// static properties
static float& samplePosScaler;
static float& samplePosRangeMin;
};
#pragma pack( pop )
class zCModelAni : public zCObject {
public:
zCLASS_DECLARATION( zCModelAni )
enum {
zMDL_ANI_FLAG_VOB_ROT = 1,
zMDL_ANI_FLAG_VOB_POS = 2,
zMDL_ANI_FLAG_END_SYNC = 4,
zMDL_ANI_FLAG_FLY = 8,
zMDL_ANI_FLAG_IDLE = 16
};
zSTRING aniName;
zSTRING ascName;
int aniID;
zSTRING aliasName;
zCList<zCModelAni> combAniList;
int layer;
float blendInSpeed;
float blendOutSpeed;
zTBBox3D aniBBox3DObjSpace;
float collisionVolumeScale;
zCModelAni* nextAni;
zSTRING nextAniName;
zCModelAniEvent* aniEvents;
float fpsRate;
float fpsRateSource;
int rootNodeIndex;
zCArray<int> nodeIndexList;
zCModelNode** nodeList;
zTMdl_AniSample* aniSampleMatrix;
float samplePosRangeMin;
float samplePosScaler;
group {
int numFrames : 16;
int numNodes : 16;
zTMdl_AniType aniType : 6;
zTMdl_AniDir aniDir : 2;
int numAniEvents : 6;
};
group {
byte flagVobRot : 1;
byte flagVobPos : 1;
byte flagEndSync : 1;
byte flagFly : 1;
byte flagIdle : 1;
byte flagInPlace : 1;
byte flagStaticCycle : 1;
}
aniFlags;
void zCModelAni_OnInit() zCall( 0x0057FBC0 );
zCModelAni() zInit( zCModelAni_OnInit() );
void PrecacheAniEventData() zCall( 0x0057FFD0 );
float GetAniVelocity() const zCall( 0x005800A0 );
zVEC3 GetAniTranslation() const zCall( 0x00580220 );
void AddTrafoMatrix( zMAT4** ) zCall( 0x00580360 );
zCQuat GetQuat( int, int ) const zCall( 0x00580800 );
zVEC3 GetTrans( int, int ) const zCall( 0x00580860 );
void SetTrans( int, int, zVEC3 const& ) zCall( 0x00580900 );
void SetQuat( int, int, zCQuat const& ) zCall( 0x00580980 );
void AddNodeList( zCTree<zCModelNode>** ) zCall( 0x00580A20 );
void SetFlags( zSTRING const& ) zCall( 0x00580A90 );
void SetBlendingSec( float, float ) zCall( 0x00580B40 );
void GetBlendingSec( float&, float& ) const zCall( 0x00580BA0 );
void CorrectRootNodeIdleMovement() zCall( 0x00580C00 );
void CalcInPlaceFlag() zCall( 0x00580D60 );
int ResolveAlias( zCModelPrototype* ) zCall( 0x00580F40 );
int ResolveComb( zCModelPrototype* ) zCall( 0x00581220 );
void SaveMAN( zCModelPrototype*, zSTRING const& ) zCall( 0x00581920 );
int LoadMAN( zSTRING const&, zCModelPrototype*, zSTRING const& ) zCall( 0x005821E0 );
zSTRING const& GetAniName() const zCall( 0x00597C00 );
zTMdl_AniType GetAniType() const zCall( 0x00597C10 );
int GetAniID() const zCall( 0x0064CF80 );
static zCObject* _CreateNewInstance() zCall( 0x005716D0 );
virtual zCClassDef* _GetClassDef() const zCall( 0x0057FD60 );
virtual ~zCModelAni() zCall( 0x0057FDA0 );
};
class zCModelPrototype {
public:
enum zTFileSourceType {
zFROM_MDS,
zFROM_ASC
};
zCModelPrototype* next;
zCModelPrototype* prev;
int refCtr;
zSTRING modelProtoName;
zSTRING modelProtoFileName;
zCTree<zCModelNode> meshTree;
zCArraySort<zCModelAni*> protoAnis;
zCArray<zCModelAniEvent*> modelEvents;
zCArray<zCModelNode*> nodeList;
unsigned long nodeListChecksum;
zCArray<zCMeshSoftSkin*> meshSoftSkinList;
zSTRING hierarchySourceASC;
zTBBox3D bbox3D;
zTBBox3D bbox3DCollDet;
zCModelPrototype* baseModelProto;
zVEC3 rootNodeTrans;
zTFileSourceType fileSourceType;
zCArray<zCMesh*> sourceMeshSoftSkinList;
void zCModelPrototype_OnInit() zCall( 0x005830B0 );
zCModelPrototype() zInit( zCModelPrototype_OnInit() );
void Init() zCall( 0x005832F0 );
~zCModelPrototype() zCall( 0x005834B0 );
void Clear() zCall( 0x005836F0 );
void ReleaseMeshSoftSkinList() zCall( 0x00583890 );
void ReleaseMeshes() zCall( 0x005838F0 );
int Release() zCall( 0x00583980 );
zSTRING const& GetModelProtoFileName() const zCall( 0x005839D0 );
void SetModelProtoName( zSTRING const& ) zCall( 0x005839E0 );
void SetFileSourceType( zTFileSourceType ) zCall( 0x00583B70 );
int PrepareAsModelProtoOverlay( zCModelPrototype* ) zCall( 0x00583F40 );
void CalcNodeListChecksum() zCall( 0x00584310 );
void CollectNodeMeshes( zCArray<zCModelNode*>& ) zCall( 0x00584370 );
zCModelNode* SearchNode( zSTRING const& ) zCall( 0x00584590 );
zCTree<zCModelNode>* FindMeshTreeNode( zSTRING const&, zCTree<zCModelNode>* ) zCall( 0x00584640 );
int FindMeshTreeNodeIndex( zSTRING const&, zCTree<zCModelNode>* ) zCall( 0x005846F0 );
int FindNodeListIndex( zSTRING const& ) zCall( 0x005847B0 );
void AddAni( zCModelAni* ) zCall( 0x00584850 );
int __fastcall SearchAniIndex( zSTRING const& ) const zCall( 0x00584A60 );
zCModelAni* SearchAni( zSTRING const& ) const zCall( 0x00584B30 );
void DescribeTree( zCTree<zCModelNode>*, int ) zCall( 0x00584B50 );
int LoadMDH( zSTRING const& ) zCall( 0x00584DA0 );
int LoadMDH( zCFileBIN& ) zCall( 0x00585000 );
void SaveMDH() zCall( 0x00585660 );
void SaveMDH( zCFileBIN& ) zCall( 0x00585860 );
void ConvertVec3( zVEC3& ) zCall( 0x00585D80 );
void ConvertAngle( float& ) zCall( 0x00585DA0 );
void SkipBlock() zCall( 0x00585DB0 );
void SkipBlockCmt() zCall( 0x00585E30 );
void ReadComment() zCall( 0x00585F00 );
void ReadScene( float& ) zCall( 0x00585F10 );
zVEC3 ReadTriple() zCall( 0x005862B0 );
zMAT4 ReadNodeTM( zCModelNode* ) zCall( 0x005864A0 );
void ReadVertexList( zCMesh*, int ) zCall( 0x00586940 );
zTMatIDList* ReadFaceList( zCMesh*, int ) zCall( 0x00586B70 );
zVEC2* ReadTVertexList( int ) zCall( 0x00587070 );
void ReadTFaceList( zCMesh*, zVEC2*, int ) zCall( 0x00587270 );
void ReadSoftSkinVertList() zCall( 0x005874E0 );
zCMesh* ReadMesh( int, zCModelNode*, int ) zCall( 0x005886A0 );
void ReadMeshAnimation( zCModelNode*, int ) zCall( 0x00588A80 );
void ReadPosTrack( zMAT4* ) zCall( 0x00588C00 );
void ReadRotTrack( zMAT4* ) zCall( 0x00588DE0 );
void ReadTMAnimation( zCModelNode*, zMAT4*& ) zCall( 0x00589090 );
void LocalizeTrafos( zCTree<zCModelNode>*, zCTree<zCModelNode>* ) zCall( 0x005896D0 );
void ReadMapDiffuse( zCMaterial* ) zCall( 0x00589800 );
zCMaterial* ReadMaterial() zCall( 0x00589C70 );
zCMaterial* ReadWireframeColor() zCall( 0x0058A2E0 );
void AssignMeshNodeMaterials( zCMesh*, zTMatIDList*, int ) zCall( 0x0058A580 );
void TransformNodeVisual( zCModelNode*, zMAT4 const& ) zCall( 0x0058A670 );
void ProcessMeshNode( zCModelNode*, zCTree<zCModelNode>*, int, int, int& ) zCall( 0x0058A6D0 );
void ReadGeomobject( zMAT4*&, zCTree<zCModelNode>*& ) zCall( 0x0058AAE0 );
void ReadMaterialList() zCall( 0x0058C060 );
void Load3DSMAXAsc( zCModelAni*&, zSTRING const&, zSTRING const&, int, int, int, float ) zCall( 0x0058C2F0 );
void CalcAniBBox( zCModelAni* ) zCall( 0x0058D370 );
void ResolveReferences() zCall( 0x0058D8A0 );
void SkipBlockMDS( int ) zCall( 0x0058DBA0 );
int ReadMeshAndTreeMSB( int&, zCFileBIN& ) zCall( 0x0058DC20 );
void ReadMeshAndTree( int&, zCFileBIN& ) zCall( 0x0058E060 );
void RegisterMesh( zCFileBIN& ) zCall( 0x0058E6E0 );
int ReadAniEnumMSB( int, zCFileBIN& ) zCall( 0x0058E970 );
void ReadAniEnum( int, zCFileBIN& ) zCall( 0x005916A0 );
int ReadModelMSB( zCFileBIN& ) zCall( 0x00597CF0 );
void ReadModel( zCFileBIN& ) zCall( 0x00597F60 );
int LoadModelScriptMSB( zSTRING const& ) zCall( 0x00598250 );
int LoadModelScript( zSTRING const& ) zCall( 0x00598870 );
int LoadModelASC( zSTRING const& ) zCall( 0x00599200 );
static int NumInList() zCall( 0x005839B0 );
static zCModelPrototype* Load( zSTRING const&, zCModelPrototype* ) zCall( 0x00583CF0 );
static zCModelPrototype* SearchName( zSTRING ) zCall( 0x005844D0 );
static unsigned long GetMDHFileVersion() zCall( 0x00584D90 );
static unsigned long GetMDSFileVersion() zCall( 0x0058DB90 );
// static properties
static int& s_ignoreAnis;
static int& s_autoConvertAnis;
static int& s_autoConvertMeshes;
static zCModelPrototype*& s_modelRoot;
};
class zCModelAniActive {
public:
zCModelAni* protoAni;
zCModelAni* nextAni;
int advanceDir;
float actFrame;
int actAniEvent;
float combAniX;
float combAniY;
int isFadingOut;
int isFirstTime;
zCModelAni* nextAniOverride;
float blendInOverride;
float blendOutOverride;
zVEC3 lastPos;
zVEC3 thisPos;
zCQuat lastRotQuat;
zCQuat thisRotQuat;
zCQuat freezeRotQuat;
int rotFirstTime;
float transWeight;
zTAniAttachment* aniAttachment;
float randAniTimer;
void zCModelAniActive_OnInit() zCall( 0x00571850 );
zCModelAniActive() zInit( zCModelAniActive_OnInit() );
~zCModelAniActive() zCall( 0x00571940 );
void SetDirection( zTMdl_AniDir ) zCall( 0x00571960 );
float GetProgressPercent() const zCall( 0x005719B0 );
void SetProgressPercent( float ) zCall( 0x005719F0 );
void SetActFrame( float ) zCall( 0x00571A40 );
void DoCombineAni( zCModel*, int, int ) zCall( 0x0057A890 );
};
class zCModelTexAniState {
public:
enum {
zMDL_MAX_ANI_CHANNELS = 2,
zMDL_MAX_TEX = 4
};
int numNodeTex;
zCTexture** nodeTexList;
int actAniFrames[zMDL_MAX_ANI_CHANNELS][zMDL_MAX_TEX];
void zCModelTexAniState_OnInit() zCall( 0x00571A90 );
zCModelTexAniState() zInit( zCModelTexAniState_OnInit() );
~zCModelTexAniState() zCall( 0x00571AB0 );
void DeleteTexList() zCall( 0x00571AD0 );
void UpdateTexList() zCall( 0x00571AF0 );
void SetChannelVariation( int, int, zSTRING* ) zCall( 0x00571B30 );
void BuildTexListFromMeshLib( zCModelMeshLib* ) zCall( 0x00571BA0 );
void BuildTexListFromMesh( zCMesh* ) zCall( 0x00571C20 );
void BuildTexListFromProgMesh( zCProgMeshProto* ) zCall( 0x00571DB0 );
void AddTexListFromMeshLib( zCModelMeshLib*, zCArray<zCTexture*>& ) zCall( 0x00571F20 );
void AddTexListFromMesh( zCMesh*, zCArray<zCTexture*>& ) zCall( 0x00572180 );
void AddTexListFromProgMesh( zCProgMeshProto*, zCArray<zCTexture*>& ) zCall( 0x005722E0 );
void FinishTexList( zCArray<zCTexture*>& ) zCall( 0x00572430 );
};
#pragma pack( push, 1 )
class zCModelNodeInst {
public:
enum {
zMDL_BLEND_STATE_FADEIN,
zMDL_BLEND_STATE_CONST,
zMDL_BLEND_STATE_FADEOUT
};
struct zTNodeAni {
zCModelAniActive* modelAni;
float weight;
float weightSpeed;
int blendState;
zCQuat quat;
zTNodeAni() {}
};
zCModelNodeInst* parentNode;
zCModelNode* protoNode;
zCVisual* nodeVisual;
zMAT4 trafo;
zMAT4 trafoObjToCam;
zTBBox3D bbox3D;
zCModelTexAniState texAniState;
zTNodeAni nodeAniList[zMDL_MAX_ANIS_PARALLEL];
int numNodeAnis;
int masterAni;
float masterAniSpeed;
void zCModelNodeInst_OnInit() zCall( 0x005725C0 );
void zCModelNodeInst_OnInit( zCModelNode* ) zCall( 0x00572690 );
zCModelNodeInst() zInit( zCModelNodeInst_OnInit() );
zCModelNodeInst( zCModelNode* a0 ) zInit( zCModelNodeInst_OnInit( a0 ));
~zCModelNodeInst() zCall( 0x00572780 );
void Init() zCall( 0x00572800 );
void InitByModelProtoNode( zCModelNode* ) zCall( 0x00572890 );
void SetNodeVisualS( zCVisual*, int ) zCall( 0x00572940 );
void AddNodeAni( zCModelAniActive* ) zCall( 0x005795D0 );
void RemoveAllNodeAnis() zCall( 0x00579800 );
void RemoveNodeAni( zCModelAniActive* ) zCall( 0x00579810 );
void FindMasterAni() zCall( 0x00579900 );
void FadeOutNodeAni( zCModelAniActive* ) zCall( 0x00579970 );
void CalcWeights( zCModel* ) zCall( 0x00579F50 );
void AddToNodeAniWeight( int, float ) zCall( 0x0057A190 );
void CalcBlending( zCModel* ) zCall( 0x0057A200 );
int GetNodeAniListIndex( zCModelAniActive const* ) const zCall( 0x0057A390 );
};
#pragma pack( pop )
struct zTRandAni {
int randAniProtoID;
int prob;
zTRandAni() {}
};
struct zTAniAttachment {
int aniID;
zCArray<zTRandAni> randAniList;
float randAniFreq;
int randAniProbSum;
void zTAniAttachment_OnInit() zCall( 0x0057DE00 );
~zTAniAttachment() zCall( 0x0057DDE0 );
zTAniAttachment() zInit( zTAniAttachment_OnInit() );
};
class zCModel : public zCVisualAnimate {
public:
zCLASS_DECLARATION( zCModel )
enum {
zMDL_DYNLIGHT_SCALEPRELIT = 0,
zMDL_DYNLIGHT_EXACT = 1
};
enum {
zMDL_STARTANI_DEFAULT,
zMDL_STARTANI_ISNEXTANI,
zMDL_STARTANI_FORCE
};
struct zTMdl_NodeVobAttachment {
public:
zCVob* vob;
zCModelNodeInst* mnode;
};
struct zTMdl_StartedVobFX {
public:
zCVob* vob;
float vobFXHandle;
};
struct zTAniMeshLibEntry {
public:
zCModelAniActive* ani;
zCModelMeshLib* meshLib;
};
struct zTMeshLibEntry {
public:
zCModelTexAniState texAniState;
zCModelMeshLib* meshLib;
};
int numActiveAnis;
zCModelAniActive* aniChannels[zMDL_MAX_ANIS_PARALLEL];
zCModelAniActive* activeAniList;
zCArray<int> m_listOfVoiceHandles;
zCVob* homeVob;
zCArray<zCModelPrototype*> modelProtoList;
zCArray<zCModelNodeInst*> nodeList;
zCArray<zCMeshSoftSkin*> meshSoftSkinList;
zCArraySort<zTAniAttachment*> aniAttachList;
zCArray<zTMdl_NodeVobAttachment>attachedVobList;
zCArray<zTMdl_StartedVobFX> startedVobFX;
zCArray<zTAniMeshLibEntry> aniMeshLibList;
zCArray<zTMeshLibEntry*> meshLibList;
int lastTimeBBox3DTreeUpdate;
zCArray<zCModelAniEvent*> occuredAniEvents;
zTBBox3D bbox3D;
zTBBox3D bbox3DLocalFixed;
zTBBox3D bbox3DCollDet;
float modelDistanceToCam;
int n_bIsInMobInteraction;
float fatness;
zVEC3 modelScale;
zVEC3 aniTransScale;
zVEC3 rootPosLocal;
zVEC3 vobTrans;
zVEC3 vobTransRing;
int newAniStarted;
int m_bSmoothRootNode;
float relaxWeight;
int m_bDrawHandVisualsOnly;
zCQuat vobRot;
zVEC3 modelVelocity;
int actVelRingPos;
zVEC3 modelVelRing[zMDL_VELRING_SIZE];
group {
unsigned char isVisible : 1;
unsigned char isFlying : 1;
unsigned char randAnisEnabled : 1;
unsigned char lerpSamples : 1;
unsigned char modelScaleOn : 1;
unsigned char doVobRot : 1;
unsigned char nodeShadowEnabled : 1;
unsigned char dynLightMode : 1;
};
float timeScale;
zCModelAni** aniHistoryList;
zCModel() {}
void zCModel_OnInit( zCModelPrototype* ) zCall( 0x00572F90 );
zCModelAni* GetAniFromAniID( int ) const zCall( 0x00471E30 );
int IsAniActive( zCModelAni* ) zCall( 0x00471E70 );
void Init() zCall( 0x00572D20 );
zCModel( zCModelPrototype* a0 ) zInit( zCModel_OnInit( a0 ));
void CopyProtoNodeList() zCall( 0x00573150 );
int ApplyModelProtoOverlay( zSTRING const& ) zCall( 0x00573540 );
int ApplyModelProtoOverlay( zCModelPrototype* ) zCall( 0x00573590 );
int HasAppliedModelProtoOverlay( zCModelPrototype* ) const zCall( 0x005737E0 );
int HasAppliedModelProtoOverlay( zSTRING const& ) const zCall( 0x00573810 );
void RemoveModelProtoOverlay( zSTRING const& ) zCall( 0x00573990 );
void RemoveModelProtoOverlay( zCModelPrototype* ) zCall( 0x00573B90 );
void CalcNodeListBBoxWorld() zCall( 0x00573D10 );
zTBBox3D GetBBox3DNodeWorld( zCModelNodeInst* ) zCall( 0x00573E40 );
zVEC3 GetNodePositionWorld( zCModelNodeInst* ) zCall( 0x00573E90 );
void CalcModelBBox3DWorld() zCall( 0x00573EC0 );
void SetNodeVisual( zCModelNodeInst*, zCVisual*, int ) zCall( 0x00573FF0 );
void SetDynLightMode( int ) zCall( 0x00574020 );
void __fastcall RenderNodeList( zTRenderContext&, zCArray<zMAT4*>&, zCRenderLightContainer&, zTPMLightingMode ) zCall( 0x00574040 );
void CheckNodeCollisionList( zCOBBox3D const&, zMAT4& ) zCall( 0x005752B0 );
void CheckNodeCollision( zCModel*, zCModelNodeInst*, zMAT4&, zCList<zCModelNodeInst>& ) zCall( 0x00575350 );
zMAT4 GetTrafoNodeToModel( zCModelNodeInst* ) zCall( 0x005754A0 );
void SetRandAnisEnabled( int ) zCall( 0x005755D0 );
zCModelAniActive* GetActiveAni( int ) const zCall( 0x00575640 );
zCModelAniActive* GetActiveAni( zCModelAni* ) const zCall( 0x00575680 );
void StopAni( int ) zCall( 0x005756C0 );
void StopAni( zCModelAni* ) zCall( 0x00575740 );
void StopAni( zCModelAniActive* ) zCall( 0x00575790 );
zVEC3 GetAniTransLerp( zCModelAni*, float, int ) const zCall( 0x00575950 );
void StartAni( zSTRING const&, int ) zCall( 0x00575A50 );
void StartAni( int, int ) zCall( 0x00575B50 );
void StartAni( zCModelAni*, int ) zCall( 0x00575BA0 );
void AssertActiveAniListAlloced() zCall( 0x00576250 );
void DoAniEvents( zCModelAniActive* ) zCall( 0x00576370 );
void __fastcall AdvanceAni( zCModelAniActive*, int& ) zCall( 0x005772B0 );
void AdvanceAnis() zCall( 0x00577570 );
void SetModelScale( zVEC3 const& ) zCall( 0x00578710 );
int IsStateActive( zCModelAni const* ) const zCall( 0x00578880 );
zCModelNodeInst* SearchNode( zSTRING const& ) zCall( 0x00578AD0 );
int SetNodeMeshTexture( zSTRING const&, int, int, zSTRING* ) zCall( 0x00578B80 );
int SetMeshLibTexture( zSTRING const&, int, int, zSTRING* ) zCall( 0x00578CB0 );
void RemoveMeshLibAll() zCall( 0x00578EB0 );
int RemoveMeshLib( zSTRING const& ) zCall( 0x00578EE0 );
int ApplyMeshLib( zSTRING const& ) zCall( 0x005790F0 );
void UpdateMeshLibTexAniState() zCall( 0x00579550 );
void FadeOutAni( int ) zCall( 0x00579A30 );
void FadeOutAni( zCModelAni* ) zCall( 0x00579AC0 );
void FadeOutAni( zCModelAniActive* ) zCall( 0x00579B00 );
void FadeOutAnisLayerRange( int, int ) zCall( 0x00579CD0 );
void StopAnisLayerRange( int, int ) zCall( 0x00579D20 );
float GetProgressPercent( zSTRING const& ) const zCall( 0x00579D70 );
float GetProgressPercent( int ) const zCall( 0x00579E20 );
void SetCombineAniXY( int, float, float ) const zCall( 0x00579E90 );
int GetCombineAniXY( int, float&, float& ) const zCall( 0x00579EE0 );
void CalcNodeListAniBlending() zCall( 0x0057A360 );
void CalcTransBlending() zCall( 0x0057A3C0 );
void AttachChildVobToNode( zCVob*, zCModelNodeInst* ) zCall( 0x0057B180 );
void RemoveChildVobFromNode( zCVob* ) zCall( 0x0057B2D0 );
void RemoveAllChildVobsFromNode() zCall( 0x0057B350 );
void UpdateAttachedVobs() zCall( 0x0057B3A0 );
void RemoveStartedVobFX( zCVob* ) zCall( 0x0057B4F0 );
zVEC3 GetVelocityRing() const zCall( 0x0057B5A0 );
void ResetVelocity() zCall( 0x0057B600 );
void GetAniMinMaxWeight( zCModelAniActive*, float&, float& ) zCall( 0x0057B690 );
void PrintStatus( int, int ) zCall( 0x0057B930 );
int CorrectAniFreezer() zCall( 0x0057C080 );
void psb_WriteAniBlock( zCBuffer&, int, int ) const zCall( 0x0057C2F0 );
void psb_ReadAniBlock( zCBuffer&, int, zCModelAniActive* ) zCall( 0x0057C480 );
void PackStateBinary( zCBuffer& ) zCall( 0x0057C6D0 );
void UnpackStateBinary( zCBuffer& ) zCall( 0x0057CA20 );
void ShowAniListAdd( zCModelAni* ) zCall( 0x0057D1A0 );
void ShowAniList( int ) zCall( 0x0057D210 );
zTAniAttachment* SearchAniAttachList( int ) const zCall( 0x0057DE40 );
void RemoveAniAttachment( int ) zCall( 0x0057DEC0 );
void RemoveAllAniAttachments() zCall( 0x0057E010 );
void RemoveAllVobFX() zCall( 0x0057E060 );
zTAniAttachment* GetCreateAniAttachment( int ) zCall( 0x0057E0F0 );
void DeleteRandAniList( int ) zCall( 0x0057E340 );
void InsertRandAni( int, int, int ) zCall( 0x0057E3D0 );
float GetRandAniFreq( int ) const zCall( 0x0057E4D0 );
void SetRandAniFreq( int, float ) zCall( 0x0057E560 );
void __fastcall RecalcRootPosLocal( int ) zCall( 0x0057E580 );
int GetAniIDFromAniName( zSTRING const& ) const zCall( 0x0060A9B0 );
static zCObject* _CreateNewInstance() zCall( 0x00571170 );
static int AniAttachmentCompare( void const*, void const* ) zCall( 0x0057DE10 );
virtual zCClassDef* _GetClassDef() const zCall( 0x00571300 );
virtual ~zCModel() zCall( 0x00572A10 );
virtual int Render( zTRenderContext& ) zCall( 0x00574FC0 );
virtual int IsBBox3DLocal() zCall( 0x00571310 );
virtual zTBBox3D GetBBox3D() zCall( 0x00578A00 );
virtual zSTRING GetVisualName() zCall( 0x00578A40 );
virtual void SetVisualUsedBy( zCVob* ) zCall( 0x00573410 );
virtual unsigned long GetRenderSortKey() const zCall( 0x0057D280 );
virtual int CanTraceRay() const zCall( 0x00571320 );
virtual int TraceRay( zVEC3 const&, zVEC3 const&, int, zTTraceRayReport& ) zCall( 0x0057D2A0 );
virtual void HostVobRemovedFromWorld( zCVob*, zCWorld* ) zCall( 0x005762C0 );
virtual zSTRING const* GetFileExtension( int ) zCall( 0x00573490 );
virtual zCVisual* LoadVisualVirtual( zSTRING const& ) const zCall( 0x005734B0 );
virtual void StartAnimation( zSTRING const& ) zCall( 0x00571330 );
virtual void StopAnimation( zSTRING const& ) zCall( 0x00571340 );
virtual int IsAnimationActive( zSTRING const& ) zCall( 0x005713E0 );
virtual zSTRING const* GetAnyAnimation() zCall( 0x00575900 );
// static properties
static int& s_drawSkeleton;
static int& s_bSmoothRootNode;
};
class zCModelConvertFileHandler : public zCScanDirFileHandler {
public:
void zCModelConvertFileHandler_OnInit() zCall( 0x0059C0B0 );
zCModelConvertFileHandler() zInit( zCModelConvertFileHandler_OnInit() );
virtual ~zCModelConvertFileHandler() zCall( 0x00424910 );
virtual int HandleFile( zSTRING const&, char const*, _finddata_t ) zCall( 0x0059C1E0 );
};
} // namespace Gothic_II_Classic
#endif // __ZMODEL_H__VER2__ | 60.44078 | 145 | 0.462445 | [
"render"
] |
ecdbd725f17870dd42a6ae097768c175d4572e0c | 3,541 | h | C | Source/Supertalk/SupertalkValue.h | mshvern/Supertalk | 9c5e8c0aefab8c72857623e83ddf53f9fc570366 | [
"MIT"
] | 21 | 2021-06-13T07:23:08.000Z | 2022-03-31T06:40:40.000Z | Source/Supertalk/SupertalkValue.h | mshvern/Supertalk | 9c5e8c0aefab8c72857623e83ddf53f9fc570366 | [
"MIT"
] | null | null | null | Source/Supertalk/SupertalkValue.h | mshvern/Supertalk | 9c5e8c0aefab8c72857623e83ddf53f9fc570366 | [
"MIT"
] | 1 | 2021-11-25T14:32:52.000Z | 2021-11-25T14:32:52.000Z | // Copyright (c) MissiveArts LLC
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataTable.h"
#include "SupertalkValue.generated.h"
class USupertalkPlayer;
UCLASS(Abstract)
class SUPERTALK_API USupertalkValue : public UObject
{
GENERATED_BODY()
public:
const USupertalkValue* GetResolvedValue(const USupertalkPlayer* Player) const;
FText ToResolvedDisplayText(const USupertalkPlayer* Player) const;
virtual FText ToDisplayText() const PURE_VIRTUAL(USupertalkValue::ToDisplayText,return FText();)
virtual const USupertalkValue* GetMember(FName MemberName) const PURE_VIRTUAL(USupertalkValue::GetMember,return nullptr;)
virtual bool IsValueEqualTo(const USupertalkValue* Other) const { return this == Other; }
protected:
virtual const USupertalkValue* ResolveValue(const USupertalkPlayer* Player) const;
};
UCLASS()
class SUPERTALK_API USupertalkBooleanValue : public USupertalkValue
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
uint8 bValue : 1;
virtual FText ToDisplayText() const override;
virtual const USupertalkValue* GetMember(FName MemberName) const override;
virtual bool IsValueEqualTo(const USupertalkValue* Other) const override;
};
UCLASS()
class SUPERTALK_API USupertalkTextValue : public USupertalkValue
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
FText Text;
virtual FText ToDisplayText() const override;
virtual const USupertalkValue* GetMember(FName MemberName) const override;
virtual bool IsValueEqualTo(const USupertalkValue* Other) const override;
};
UCLASS()
class SUPERTALK_API USupertalkVariableValue : public USupertalkValue
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
FName Variable;
virtual FText ToDisplayText() const override;
virtual const USupertalkValue* GetMember(FName MemberName) const override;
virtual bool IsValueEqualTo(const USupertalkValue* Other) const override { checkNoEntry(); return false; }
protected:
virtual const USupertalkValue* ResolveValue(const USupertalkPlayer* Player) const override;
};
// This should be replaced with an expression at some point.
UCLASS()
class SUPERTALK_API USupertalkMemberValue : public USupertalkVariableValue
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
TArray<FName> Members;
virtual FText ToDisplayText() const override;
virtual const USupertalkValue* GetMember(FName MemberName) const override;
virtual bool IsValueEqualTo(const USupertalkValue* Other) const override { checkNoEntry(); return false; }
protected:
virtual const USupertalkValue* ResolveValue(const USupertalkPlayer* Player) const override;
};
UINTERFACE()
class USupertalkDisplayInterface : public UInterface
{
GENERATED_BODY()
};
class SUPERTALK_API ISupertalkDisplayInterface
{
GENERATED_BODY()
public:
// Get the text to be displayed for this object for a supertalk line.
virtual FText GetSupertalkDisplayText() const;
// Get a sub-member of this object.
virtual const USupertalkValue* GetSupertalkMember(FName MemberName) const;
};
UCLASS()
class SUPERTALK_API USupertalkObjectValue : public USupertalkValue
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere)
TObjectPtr<UObject> Object;
virtual FText ToDisplayText() const override;
virtual const USupertalkValue* GetMember(FName MemberName) const override;
virtual bool IsValueEqualTo(const USupertalkValue* Other) const override;
};
USTRUCT(BlueprintType)
struct SUPERTALK_API FSupertalkTableRow : public FTableRowBase
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FText Value;
}; | 25.846715 | 122 | 0.807964 | [
"object"
] |
ecdf134dc59ebe1c2933846d9be7f3fad29bd1e9 | 15,311 | h | C | shared/protobuf/Models/characteristic.pb.h | cvrebeatsaber/QuestQualifications | 4be76c3e8da9ead1727e2320fd12c083aabdacad | [
"MIT"
] | 1 | 2020-10-07T06:39:16.000Z | 2020-10-07T06:39:16.000Z | shared/protobuf/Models/characteristic.pb.h | cvrebeatsaber/QuestQualifications | 4be76c3e8da9ead1727e2320fd12c083aabdacad | [
"MIT"
] | null | null | null | shared/protobuf/Models/characteristic.pb.h | cvrebeatsaber/QuestQualifications | 4be76c3e8da9ead1727e2320fd12c083aabdacad | [
"MIT"
] | 1 | 2021-06-02T23:13:46.000Z | 2021-06-02T23:13:46.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: protobuf/Models/characteristic.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_protobuf_2fModels_2fcharacteristic_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_protobuf_2fModels_2fcharacteristic_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3015000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3015006 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include "protobuf/Models/beatmap_difficulty.pb.h"
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_protobuf_2fModels_2fcharacteristic_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_protobuf_2fModels_2fcharacteristic_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_protobuf_2fModels_2fcharacteristic_2eproto;
::PROTOBUF_NAMESPACE_ID::Metadata descriptor_table_protobuf_2fModels_2fcharacteristic_2eproto_metadata_getter(int index);
namespace TournamentAssistantShared {
namespace Models {
class Characteristic;
struct CharacteristicDefaultTypeInternal;
extern CharacteristicDefaultTypeInternal _Characteristic_default_instance_;
} // namespace Models
} // namespace TournamentAssistantShared
PROTOBUF_NAMESPACE_OPEN
template<> ::TournamentAssistantShared::Models::Characteristic* Arena::CreateMaybeMessage<::TournamentAssistantShared::Models::Characteristic>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace TournamentAssistantShared {
namespace Models {
// ===================================================================
class Characteristic PROTOBUF_FINAL :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:TournamentAssistantShared.Models.Characteristic) */ {
public:
inline Characteristic() : Characteristic(nullptr) {}
virtual ~Characteristic();
explicit constexpr Characteristic(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
Characteristic(const Characteristic& from);
Characteristic(Characteristic&& from) noexcept
: Characteristic() {
*this = ::std::move(from);
}
inline Characteristic& operator=(const Characteristic& from) {
CopyFrom(from);
return *this;
}
inline Characteristic& operator=(Characteristic&& from) noexcept {
if (GetArena() == from.GetArena()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const Characteristic& default_instance() {
return *internal_default_instance();
}
static inline const Characteristic* internal_default_instance() {
return reinterpret_cast<const Characteristic*>(
&_Characteristic_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(Characteristic& a, Characteristic& b) {
a.Swap(&b);
}
inline void Swap(Characteristic* other) {
if (other == this) return;
if (GetArena() == other->GetArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(Characteristic* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArena() == other->GetArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline Characteristic* New() const final {
return CreateMaybeMessage<Characteristic>(nullptr);
}
Characteristic* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<Characteristic>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const Characteristic& from);
void MergeFrom(const Characteristic& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(Characteristic* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "TournamentAssistantShared.Models.Characteristic";
}
protected:
explicit Characteristic(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
return ::descriptor_table_protobuf_2fModels_2fcharacteristic_2eproto_metadata_getter(kIndexInFileMessages);
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kDifficultiesFieldNumber = 2,
kSerializedNameFieldNumber = 1,
};
// repeated .TournamentAssistantShared.Models.BeatmapDifficulty difficulties = 2;
int difficulties_size() const;
private:
int _internal_difficulties_size() const;
public:
void clear_difficulties();
private:
::TournamentAssistantShared::Models::BeatmapDifficulty _internal_difficulties(int index) const;
void _internal_add_difficulties(::TournamentAssistantShared::Models::BeatmapDifficulty value);
::PROTOBUF_NAMESPACE_ID::RepeatedField<int>* _internal_mutable_difficulties();
public:
::TournamentAssistantShared::Models::BeatmapDifficulty difficulties(int index) const;
void set_difficulties(int index, ::TournamentAssistantShared::Models::BeatmapDifficulty value);
void add_difficulties(::TournamentAssistantShared::Models::BeatmapDifficulty value);
const ::PROTOBUF_NAMESPACE_ID::RepeatedField<int>& difficulties() const;
::PROTOBUF_NAMESPACE_ID::RepeatedField<int>* mutable_difficulties();
// string serialized_name = 1;
void clear_serialized_name();
const std::string& serialized_name() const;
void set_serialized_name(const std::string& value);
void set_serialized_name(std::string&& value);
void set_serialized_name(const char* value);
void set_serialized_name(const char* value, size_t size);
std::string* mutable_serialized_name();
std::string* release_serialized_name();
void set_allocated_serialized_name(std::string* serialized_name);
private:
const std::string& _internal_serialized_name() const;
void _internal_set_serialized_name(const std::string& value);
std::string* _internal_mutable_serialized_name();
public:
// @@protoc_insertion_point(class_scope:TournamentAssistantShared.Models.Characteristic)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedField<int> difficulties_;
mutable std::atomic<int> _difficulties_cached_byte_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr serialized_name_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_protobuf_2fModels_2fcharacteristic_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Characteristic
// string serialized_name = 1;
inline void Characteristic::clear_serialized_name() {
serialized_name_.ClearToEmpty();
}
inline const std::string& Characteristic::serialized_name() const {
// @@protoc_insertion_point(field_get:TournamentAssistantShared.Models.Characteristic.serialized_name)
return _internal_serialized_name();
}
inline void Characteristic::set_serialized_name(const std::string& value) {
_internal_set_serialized_name(value);
// @@protoc_insertion_point(field_set:TournamentAssistantShared.Models.Characteristic.serialized_name)
}
inline std::string* Characteristic::mutable_serialized_name() {
// @@protoc_insertion_point(field_mutable:TournamentAssistantShared.Models.Characteristic.serialized_name)
return _internal_mutable_serialized_name();
}
inline const std::string& Characteristic::_internal_serialized_name() const {
return serialized_name_.Get();
}
inline void Characteristic::_internal_set_serialized_name(const std::string& value) {
serialized_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena());
}
inline void Characteristic::set_serialized_name(std::string&& value) {
serialized_name_.Set(
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena());
// @@protoc_insertion_point(field_set_rvalue:TournamentAssistantShared.Models.Characteristic.serialized_name)
}
inline void Characteristic::set_serialized_name(const char* value) {
GOOGLE_DCHECK(value != nullptr);
serialized_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena());
// @@protoc_insertion_point(field_set_char:TournamentAssistantShared.Models.Characteristic.serialized_name)
}
inline void Characteristic::set_serialized_name(const char* value,
size_t size) {
serialized_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(
reinterpret_cast<const char*>(value), size), GetArena());
// @@protoc_insertion_point(field_set_pointer:TournamentAssistantShared.Models.Characteristic.serialized_name)
}
inline std::string* Characteristic::_internal_mutable_serialized_name() {
return serialized_name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena());
}
inline std::string* Characteristic::release_serialized_name() {
// @@protoc_insertion_point(field_release:TournamentAssistantShared.Models.Characteristic.serialized_name)
return serialized_name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena());
}
inline void Characteristic::set_allocated_serialized_name(std::string* serialized_name) {
if (serialized_name != nullptr) {
} else {
}
serialized_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), serialized_name,
GetArena());
// @@protoc_insertion_point(field_set_allocated:TournamentAssistantShared.Models.Characteristic.serialized_name)
}
// repeated .TournamentAssistantShared.Models.BeatmapDifficulty difficulties = 2;
inline int Characteristic::_internal_difficulties_size() const {
return difficulties_.size();
}
inline int Characteristic::difficulties_size() const {
return _internal_difficulties_size();
}
inline void Characteristic::clear_difficulties() {
difficulties_.Clear();
}
inline ::TournamentAssistantShared::Models::BeatmapDifficulty Characteristic::_internal_difficulties(int index) const {
return static_cast< ::TournamentAssistantShared::Models::BeatmapDifficulty >(difficulties_.Get(index));
}
inline ::TournamentAssistantShared::Models::BeatmapDifficulty Characteristic::difficulties(int index) const {
// @@protoc_insertion_point(field_get:TournamentAssistantShared.Models.Characteristic.difficulties)
return _internal_difficulties(index);
}
inline void Characteristic::set_difficulties(int index, ::TournamentAssistantShared::Models::BeatmapDifficulty value) {
difficulties_.Set(index, value);
// @@protoc_insertion_point(field_set:TournamentAssistantShared.Models.Characteristic.difficulties)
}
inline void Characteristic::_internal_add_difficulties(::TournamentAssistantShared::Models::BeatmapDifficulty value) {
difficulties_.Add(value);
}
inline void Characteristic::add_difficulties(::TournamentAssistantShared::Models::BeatmapDifficulty value) {
// @@protoc_insertion_point(field_add:TournamentAssistantShared.Models.Characteristic.difficulties)
_internal_add_difficulties(value);
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField<int>&
Characteristic::difficulties() const {
// @@protoc_insertion_point(field_list:TournamentAssistantShared.Models.Characteristic.difficulties)
return difficulties_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField<int>*
Characteristic::_internal_mutable_difficulties() {
return &difficulties_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedField<int>*
Characteristic::mutable_difficulties() {
// @@protoc_insertion_point(field_mutable_list:TournamentAssistantShared.Models.Characteristic.difficulties)
return _internal_mutable_difficulties();
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace Models
} // namespace TournamentAssistantShared
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_protobuf_2fModels_2fcharacteristic_2eproto
| 42.179063 | 151 | 0.776239 | [
"object"
] |
ece37b69f6c63f9c211782a252483cec5e173225 | 672,345 | h | C | renderdoc/driver/metal/official/metal-cpp.h | yanjifa/renderdoc | 308456535f067df15be78de145440c170c2d8c00 | [
"MIT"
] | 1 | 2022-02-17T21:18:24.000Z | 2022-02-17T21:18:24.000Z | renderdoc/driver/metal/official/metal-cpp.h | superlee1/renderdoc | a51b20369f685b4e57ccd97fe203483c6d5c5d1f | [
"MIT"
] | null | null | null | renderdoc/driver/metal/official/metal-cpp.h | superlee1/renderdoc | a51b20369f685b4e57ccd97fe203483c6d5c5d1f | [
"MIT"
] | null | null | null | //
// Metal.hpp
//
// Autogenerated on December 09, 2021.
//
// Copyright 2020-2021 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#define _NS_WEAK_IMPORT __attribute__((weak_import))
#define _NS_EXPORT __attribute__((visibility("default")))
#define _NS_EXTERN extern "C" _NS_EXPORT
#define _NS_INLINE inline __attribute__((always_inline))
#define _NS_PACKED __attribute__((packed))
#define _NS_CONST(type, name) _NS_EXTERN type const name;
#define _NS_ENUM(type, name) enum name : type
#define _NS_OPTIONS(type, name) \
using name = type; \
enum : name
#define _NS_CAST_TO_UINT(value) static_cast<NS::UInteger>(value)
#define _NS_VALIDATE_SIZE(ns, name) static_assert(sizeof(ns::name) == sizeof(ns##name), "size mismatch " #ns "::" #name)
#define _NS_VALIDATE_ENUM(ns, name) static_assert(_NS_CAST_TO_UINT(ns::name) == _NS_CAST_TO_UINT(ns##name), "value mismatch " #ns "::" #name)
#include <objc/runtime.h>
#define _NS_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol)
#define _NS_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor)
#if defined(NS_PRIVATE_IMPLEMENTATION)
#define _NS_PRIVATE_VISIBILITY __attribute__((visibility("default")))
#define _NS_PRIVATE_IMPORT __attribute__((weak_import))
#if __OBJC__
#define _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol))
#else
#define _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol)
#endif // __OBJC__
#define _NS_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _NS_PRIVATE_VISIBILITY = _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol);
#define _NS_PRIVATE_DEF_PRO(symbol)
#define _NS_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _NS_PRIVATE_VISIBILITY = sel_registerName(symbol);
#define _NS_PRIVATE_DEF_CONST(type, symbol) \
_NS_EXTERN type const NS##symbol _NS_PRIVATE_IMPORT; \
type const NS::symbol = (nullptr != &NS##symbol) ? NS##symbol : nullptr;
#else
#define _NS_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol;
#define _NS_PRIVATE_DEF_PRO(symbol)
#define _NS_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor;
#define _NS_PRIVATE_DEF_CONST(type, symbol)
#endif // NS_PRIVATE_IMPLEMENTATION
namespace NS
{
namespace Private
{
namespace Class
{
_NS_PRIVATE_DEF_CLS(NSArray);
_NS_PRIVATE_DEF_CLS(NSAutoreleasePool);
_NS_PRIVATE_DEF_CLS(NSBundle);
_NS_PRIVATE_DEF_CLS(NSCondition);
_NS_PRIVATE_DEF_CLS(NSDate);
_NS_PRIVATE_DEF_CLS(NSDictionary);
_NS_PRIVATE_DEF_CLS(NSError);
_NS_PRIVATE_DEF_CLS(NSNumber);
_NS_PRIVATE_DEF_CLS(NSObject);
_NS_PRIVATE_DEF_CLS(NSProcessInfo);
_NS_PRIVATE_DEF_CLS(NSString);
_NS_PRIVATE_DEF_CLS(NSURL);
_NS_PRIVATE_DEF_CLS(NSValue);
} // Class
} // Private
} // MTL
namespace NS
{
namespace Private
{
namespace Protocol
{
} // Protocol
} // Private
} // NS
namespace NS
{
namespace Private
{
namespace Selector
{
_NS_PRIVATE_DEF_SEL(addObject_,
"addObject:");
_NS_PRIVATE_DEF_SEL(activeProcessorCount,
"activeProcessorCount");
_NS_PRIVATE_DEF_SEL(allBundles,
"allBundles");
_NS_PRIVATE_DEF_SEL(allFrameworks,
"allFrameworks");
_NS_PRIVATE_DEF_SEL(allObjects,
"allObjects");
_NS_PRIVATE_DEF_SEL(alloc,
"alloc");
_NS_PRIVATE_DEF_SEL(appStoreReceiptURL,
"appStoreReceiptURL");
_NS_PRIVATE_DEF_SEL(arguments,
"arguments");
_NS_PRIVATE_DEF_SEL(array,
"array");
_NS_PRIVATE_DEF_SEL(arrayWithObject_,
"arrayWithObject:");
_NS_PRIVATE_DEF_SEL(arrayWithObjects_count_,
"arrayWithObjects:count:");
_NS_PRIVATE_DEF_SEL(automaticTerminationSupportEnabled,
"automaticTerminationSupportEnabled");
_NS_PRIVATE_DEF_SEL(autorelease,
"autorelease");
_NS_PRIVATE_DEF_SEL(beginActivityWithOptions_reason_,
"beginActivityWithOptions:reason:");
_NS_PRIVATE_DEF_SEL(boolValue,
"boolValue");
_NS_PRIVATE_DEF_SEL(broadcast,
"broadcast");
_NS_PRIVATE_DEF_SEL(builtInPlugInsPath,
"builtInPlugInsPath");
_NS_PRIVATE_DEF_SEL(builtInPlugInsURL,
"builtInPlugInsURL");
_NS_PRIVATE_DEF_SEL(bundleIdentifier,
"bundleIdentifier");
_NS_PRIVATE_DEF_SEL(bundlePath,
"bundlePath");
_NS_PRIVATE_DEF_SEL(bundleURL,
"bundleURL");
_NS_PRIVATE_DEF_SEL(bundleWithPath_,
"bundleWithPath:");
_NS_PRIVATE_DEF_SEL(bundleWithURL_,
"bundleWithURL:");
_NS_PRIVATE_DEF_SEL(characterAtIndex_,
"characterAtIndex:");
_NS_PRIVATE_DEF_SEL(charValue,
"charValue");
_NS_PRIVATE_DEF_SEL(countByEnumeratingWithState_objects_count_,
"countByEnumeratingWithState:objects:count:");
_NS_PRIVATE_DEF_SEL(cStringUsingEncoding_,
"cStringUsingEncoding:");
_NS_PRIVATE_DEF_SEL(code,
"code");
_NS_PRIVATE_DEF_SEL(compare_,
"compare:");
_NS_PRIVATE_DEF_SEL(copy,
"copy");
_NS_PRIVATE_DEF_SEL(count,
"count");
_NS_PRIVATE_DEF_SEL(dateWithTimeIntervalSinceNow_,
"dateWithTimeIntervalSinceNow:");
_NS_PRIVATE_DEF_SEL(descriptionWithLocale_,
"descriptionWithLocale:");
_NS_PRIVATE_DEF_SEL(disableAutomaticTermination_,
"disableAutomaticTermination:");
_NS_PRIVATE_DEF_SEL(disableSuddenTermination,
"disableSuddenTermination");
_NS_PRIVATE_DEF_SEL(debugDescription,
"debugDescription");
_NS_PRIVATE_DEF_SEL(description,
"description");
_NS_PRIVATE_DEF_SEL(dictionary,
"dictionary");
_NS_PRIVATE_DEF_SEL(dictionaryWithObject_forKey_,
"dictionaryWithObject:forKey:");
_NS_PRIVATE_DEF_SEL(dictionaryWithObjects_forKeys_count_,
"dictionaryWithObjects:forKeys:count:");
_NS_PRIVATE_DEF_SEL(domain,
"domain");
_NS_PRIVATE_DEF_SEL(doubleValue,
"doubleValue");
_NS_PRIVATE_DEF_SEL(drain,
"drain");
_NS_PRIVATE_DEF_SEL(enableAutomaticTermination_,
"enableAutomaticTermination:");
_NS_PRIVATE_DEF_SEL(enableSuddenTermination,
"enableSuddenTermination");
_NS_PRIVATE_DEF_SEL(endActivity_,
"endActivity:");
_NS_PRIVATE_DEF_SEL(environment,
"environment");
_NS_PRIVATE_DEF_SEL(errorWithDomain_code_userInfo_,
"errorWithDomain:code:userInfo:");
_NS_PRIVATE_DEF_SEL(executablePath,
"executablePath");
_NS_PRIVATE_DEF_SEL(executableURL,
"executableURL");
_NS_PRIVATE_DEF_SEL(fileSystemRepresentation,
"fileSystemRepresentation");
_NS_PRIVATE_DEF_SEL(fileURLWithPath_,
"fileURLWithPath:");
_NS_PRIVATE_DEF_SEL(floatValue,
"floatValue");
_NS_PRIVATE_DEF_SEL(fullUserName,
"fullUserName");
_NS_PRIVATE_DEF_SEL(getValue_size_,
"getValue:size:");
_NS_PRIVATE_DEF_SEL(globallyUniqueString,
"globallyUniqueString");
_NS_PRIVATE_DEF_SEL(hash,
"hash");
_NS_PRIVATE_DEF_SEL(hostName,
"hostName");
_NS_PRIVATE_DEF_SEL(infoDictionary,
"infoDictionary");
_NS_PRIVATE_DEF_SEL(init,
"init");
_NS_PRIVATE_DEF_SEL(initFileURLWithPath_,
"initFileURLWithPath:");
_NS_PRIVATE_DEF_SEL(initWithBool_,
"initWithBool:");
_NS_PRIVATE_DEF_SEL(initWithBytes_objCType_,
"initWithBytes:objCType:");
_NS_PRIVATE_DEF_SEL(initWithBytesNoCopy_length_encoding_freeWhenDone_,
"initWithBytesNoCopy:length:encoding:freeWhenDone:");
_NS_PRIVATE_DEF_SEL(initWithChar_,
"initWithChar:");
_NS_PRIVATE_DEF_SEL(initWithCoder_,
"initWithCoder:");
_NS_PRIVATE_DEF_SEL(initWithCString_encoding_,
"initWithCString:encoding:");
_NS_PRIVATE_DEF_SEL(initWithDomain_code_userInfo_,
"initWithDomain:code:userInfo:");
_NS_PRIVATE_DEF_SEL(initWithDouble_,
"initWithDouble:");
_NS_PRIVATE_DEF_SEL(initWithFloat_,
"initWithFloat:");
_NS_PRIVATE_DEF_SEL(initWithInt_,
"initWithInt:");
_NS_PRIVATE_DEF_SEL(initWithLong_,
"initWithLong:");
_NS_PRIVATE_DEF_SEL(initWithLongLong_,
"initWithLongLong:");
_NS_PRIVATE_DEF_SEL(initWithObjects_count_,
"initWithObjects:count:");
_NS_PRIVATE_DEF_SEL(initWithObjects_forKeys_count_,
"initWithObjects:forKeys:count:");
_NS_PRIVATE_DEF_SEL(initWithPath_,
"initWithPath:");
_NS_PRIVATE_DEF_SEL(initWithShort_,
"initWithShort:");
_NS_PRIVATE_DEF_SEL(initWithString_,
"initWithString:");
_NS_PRIVATE_DEF_SEL(initWithUnsignedChar_,
"initWithUnsignedChar:");
_NS_PRIVATE_DEF_SEL(initWithUnsignedInt_,
"initWithUnsignedInt:");
_NS_PRIVATE_DEF_SEL(initWithUnsignedLong_,
"initWithUnsignedLong:");
_NS_PRIVATE_DEF_SEL(initWithUnsignedLongLong_,
"initWithUnsignedLongLong:");
_NS_PRIVATE_DEF_SEL(initWithUnsignedShort_,
"initWithUnsignedShort:");
_NS_PRIVATE_DEF_SEL(initWithURL_,
"initWithURL:");
_NS_PRIVATE_DEF_SEL(integerValue,
"integerValue");
_NS_PRIVATE_DEF_SEL(intValue,
"intValue");
_NS_PRIVATE_DEF_SEL(isEqual_,
"isEqual:");
_NS_PRIVATE_DEF_SEL(isEqualToNumber_,
"isEqualToNumber:");
_NS_PRIVATE_DEF_SEL(isEqualToString_,
"isEqualToString:");
_NS_PRIVATE_DEF_SEL(isEqualToValue_,
"isEqualToValue:");
_NS_PRIVATE_DEF_SEL(isiOSAppOnMac,
"isiOSAppOnMac");
_NS_PRIVATE_DEF_SEL(isLoaded,
"isLoaded");
_NS_PRIVATE_DEF_SEL(isLowPowerModeEnabled,
"isLowPowerModeEnabled");
_NS_PRIVATE_DEF_SEL(isMacCatalystApp,
"isMacCatalystApp");
_NS_PRIVATE_DEF_SEL(isOperatingSystemAtLeastVersion_,
"isOperatingSystemAtLeastVersion:");
_NS_PRIVATE_DEF_SEL(keyEnumerator,
"keyEnumerator");
_NS_PRIVATE_DEF_SEL(length,
"length");
_NS_PRIVATE_DEF_SEL(lengthOfBytesUsingEncoding_,
"lengthOfBytesUsingEncoding:");
_NS_PRIVATE_DEF_SEL(load,
"load");
_NS_PRIVATE_DEF_SEL(loadAndReturnError_,
"loadAndReturnError:");
_NS_PRIVATE_DEF_SEL(localizedDescription,
"localizedDescription");
_NS_PRIVATE_DEF_SEL(localizedFailureReason,
"localizedFailureReason");
_NS_PRIVATE_DEF_SEL(localizedInfoDictionary,
"localizedInfoDictionary");
_NS_PRIVATE_DEF_SEL(localizedRecoveryOptions,
"localizedRecoveryOptions");
_NS_PRIVATE_DEF_SEL(localizedRecoverySuggestion,
"localizedRecoverySuggestion");
_NS_PRIVATE_DEF_SEL(localizedStringForKey_value_table_,
"localizedStringForKey:value:table:");
_NS_PRIVATE_DEF_SEL(lock,
"lock");
_NS_PRIVATE_DEF_SEL(longValue,
"longValue");
_NS_PRIVATE_DEF_SEL(longLongValue,
"longLongValue");
_NS_PRIVATE_DEF_SEL(mainBundle,
"mainBundle");
_NS_PRIVATE_DEF_SEL(maximumLengthOfBytesUsingEncoding_,
"maximumLengthOfBytesUsingEncoding:");
_NS_PRIVATE_DEF_SEL(methodSignatureForSelector_,
"methodSignatureForSelector:");
_NS_PRIVATE_DEF_SEL(mutableBytes,
"mutableBytes");
_NS_PRIVATE_DEF_SEL(name,
"name");
_NS_PRIVATE_DEF_SEL(nextObject,
"nextObject");
_NS_PRIVATE_DEF_SEL(numberWithBool_,
"numberWithBool:");
_NS_PRIVATE_DEF_SEL(numberWithChar_,
"numberWithChar:");
_NS_PRIVATE_DEF_SEL(numberWithDouble_,
"numberWithDouble:");
_NS_PRIVATE_DEF_SEL(numberWithFloat_,
"numberWithFloat:");
_NS_PRIVATE_DEF_SEL(numberWithInt_,
"numberWithInt:");
_NS_PRIVATE_DEF_SEL(numberWithLong_,
"numberWithLong:");
_NS_PRIVATE_DEF_SEL(numberWithLongLong_,
"numberWithLongLong:");
_NS_PRIVATE_DEF_SEL(numberWithShort_,
"numberWithShort:");
_NS_PRIVATE_DEF_SEL(numberWithUnsignedChar_,
"numberWithUnsignedChar:");
_NS_PRIVATE_DEF_SEL(numberWithUnsignedInt_,
"numberWithUnsignedInt:");
_NS_PRIVATE_DEF_SEL(numberWithUnsignedLong_,
"numberWithUnsignedLong:");
_NS_PRIVATE_DEF_SEL(numberWithUnsignedLongLong_,
"numberWithUnsignedLongLong:");
_NS_PRIVATE_DEF_SEL(numberWithUnsignedShort_,
"numberWithUnsignedShort:");
_NS_PRIVATE_DEF_SEL(objCType,
"objCType");
_NS_PRIVATE_DEF_SEL(object,
"object");
_NS_PRIVATE_DEF_SEL(objectAtIndex_,
"objectAtIndex:");
_NS_PRIVATE_DEF_SEL(objectForInfoDictionaryKey_,
"objectForInfoDictionaryKey:");
_NS_PRIVATE_DEF_SEL(objectForKey_,
"objectForKey:");
_NS_PRIVATE_DEF_SEL(operatingSystem,
"operatingSystem");
_NS_PRIVATE_DEF_SEL(operatingSystemVersion,
"operatingSystemVersion");
_NS_PRIVATE_DEF_SEL(operatingSystemVersionString,
"operatingSystemVersionString");
_NS_PRIVATE_DEF_SEL(pathForAuxiliaryExecutable_,
"pathForAuxiliaryExecutable:");
_NS_PRIVATE_DEF_SEL(performActivityWithOptions_reason_usingBlock_,
"performActivityWithOptions:reason:usingBlock:");
_NS_PRIVATE_DEF_SEL(performExpiringActivityWithReason_usingBlock_,
"performExpiringActivityWithReason:usingBlock:");
_NS_PRIVATE_DEF_SEL(physicalMemory,
"physicalMemory");
_NS_PRIVATE_DEF_SEL(pointerValue,
"pointerValue");
_NS_PRIVATE_DEF_SEL(preflightAndReturnError_,
"preflightAndReturnError:");
_NS_PRIVATE_DEF_SEL(privateFrameworksPath,
"privateFrameworksPath");
_NS_PRIVATE_DEF_SEL(privateFrameworksURL,
"privateFrameworksURL");
_NS_PRIVATE_DEF_SEL(processIdentifier,
"processIdentifier");
_NS_PRIVATE_DEF_SEL(processInfo,
"processInfo");
_NS_PRIVATE_DEF_SEL(processName,
"processName");
_NS_PRIVATE_DEF_SEL(processorCount,
"processorCount");
_NS_PRIVATE_DEF_SEL(rangeOfString_options_,
"rangeOfString:options:");
_NS_PRIVATE_DEF_SEL(release,
"release");
_NS_PRIVATE_DEF_SEL(resourcePath,
"resourcePath");
_NS_PRIVATE_DEF_SEL(resourceURL,
"resourceURL");
_NS_PRIVATE_DEF_SEL(respondsToSelector_,
"respondsToSelector:");
_NS_PRIVATE_DEF_SEL(retain,
"retain");
_NS_PRIVATE_DEF_SEL(retainCount,
"retainCount");
_NS_PRIVATE_DEF_SEL(setAutomaticTerminationSupportEnabled_,
"setAutomaticTerminationSupportEnabled:");
_NS_PRIVATE_DEF_SEL(setProcessName_,
"setProcessName:");
_NS_PRIVATE_DEF_SEL(sharedFrameworksPath,
"sharedFrameworksPath");
_NS_PRIVATE_DEF_SEL(sharedFrameworksURL,
"sharedFrameworksURL");
_NS_PRIVATE_DEF_SEL(sharedSupportPath,
"sharedSupportPath");
_NS_PRIVATE_DEF_SEL(sharedSupportURL,
"sharedSupportURL");
_NS_PRIVATE_DEF_SEL(shortValue,
"shortValue");
_NS_PRIVATE_DEF_SEL(showPools,
"showPools");
_NS_PRIVATE_DEF_SEL(signal,
"signal");
_NS_PRIVATE_DEF_SEL(string,
"string");
_NS_PRIVATE_DEF_SEL(stringValue,
"stringValue");
_NS_PRIVATE_DEF_SEL(stringWithString_,
"stringWithString:");
_NS_PRIVATE_DEF_SEL(stringWithCString_encoding_,
"stringWithCString:encoding:");
_NS_PRIVATE_DEF_SEL(stringByAppendingString_,
"stringByAppendingString:");
_NS_PRIVATE_DEF_SEL(systemUptime,
"systemUptime");
_NS_PRIVATE_DEF_SEL(thermalState,
"thermalState");
_NS_PRIVATE_DEF_SEL(unload,
"unload");
_NS_PRIVATE_DEF_SEL(unlock,
"unlock");
_NS_PRIVATE_DEF_SEL(unsignedCharValue,
"unsignedCharValue");
_NS_PRIVATE_DEF_SEL(unsignedIntegerValue,
"unsignedIntegerValue");
_NS_PRIVATE_DEF_SEL(unsignedIntValue,
"unsignedIntValue");
_NS_PRIVATE_DEF_SEL(unsignedLongValue,
"unsignedLongValue");
_NS_PRIVATE_DEF_SEL(unsignedLongLongValue,
"unsignedLongLongValue");
_NS_PRIVATE_DEF_SEL(unsignedShortValue,
"unsignedShortValue");
_NS_PRIVATE_DEF_SEL(URLForAuxiliaryExecutable_,
"URLForAuxiliaryExecutable:");
_NS_PRIVATE_DEF_SEL(userInfo,
"userInfo");
_NS_PRIVATE_DEF_SEL(userName,
"userName");
_NS_PRIVATE_DEF_SEL(UTF8String,
"UTF8String");
_NS_PRIVATE_DEF_SEL(valueWithBytes_objCType_,
"valueWithBytes:objCType:");
_NS_PRIVATE_DEF_SEL(valueWithPointer_,
"valueWithPointer:");
_NS_PRIVATE_DEF_SEL(wait,
"wait");
_NS_PRIVATE_DEF_SEL(waitUntilDate_,
"waitUntilDate:");
} // Class
} // Private
} // MTL
#include <CoreFoundation/CoreFoundation.h>
#include <cstdint>
namespace NS
{
using TimeInterval = double;
using Integer = std::int64_t;
using UInteger = std::uint64_t;
const Integer IntegerMax = INTPTR_MAX;
const Integer IntegerMin = INTPTR_MIN;
const UInteger UIntegerMax = UINTPTR_MAX;
struct OperatingSystemVersion
{
Integer majorVersion;
Integer minorVersion;
Integer patchVersion;
} _NS_PACKED;
}
#include <objc/message.h>
#include <objc/runtime.h>
#include <type_traits>
namespace NS
{
template <class _Class, class _Base = class Object>
class Referencing : public _Base
{
public:
_Class* retain();
void release();
_Class* autorelease();
UInteger retainCount() const;
};
template <class _Class, class _Base = class Object>
class Copying : public Referencing<_Class, _Base>
{
public:
_Class* copy() const;
};
class Object : public Referencing<Object, objc_object>
{
public:
UInteger hash() const;
bool isEqual(const Object* pObject) const;
class String* description() const;
class String* debugDescription() const;
protected:
friend class Referencing<Object, objc_object>;
template <class _Class>
static _Class* alloc(const char* pClassName);
template <class _Class>
static _Class* alloc(const void* pClass);
template <class _Class>
_Class* init();
template <class _Dst>
static _Dst bridgingCast(const void* pObj);
static class MethodSignature* methodSignatureForSelector(const void* pObj, SEL selector);
static bool respondsToSelector(const void* pObj, SEL selector);
template <typename _Type>
static constexpr bool doesRequireMsgSendStret();
template <typename _Ret, typename... _Args>
static _Ret sendMessage(const void* pObj, SEL selector, _Args... args);
template <typename _Ret, typename... _Args>
static _Ret sendMessageSafe(const void* pObj, SEL selector, _Args... args);
private:
Object() = delete;
Object(const Object&) = delete;
~Object() = delete;
Object& operator=(const Object&) = delete;
};
}
template <class _Class, class _Base /* = Object */>
_NS_INLINE _Class* NS::Referencing<_Class, _Base>::retain()
{
return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(retain));
}
template <class _Class, class _Base /* = Object */>
_NS_INLINE void NS::Referencing<_Class, _Base>::release()
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(release));
}
template <class _Class, class _Base /* = Object */>
_NS_INLINE _Class* NS::Referencing<_Class, _Base>::autorelease()
{
return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(autorelease));
}
template <class _Class, class _Base /* = Object */>
_NS_INLINE NS::UInteger NS::Referencing<_Class, _Base>::retainCount() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(retainCount));
}
template <class _Class, class _Base /* = Object */>
_NS_INLINE _Class* NS::Copying<_Class, _Base>::copy() const
{
return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(copy));
}
template <class _Dst>
_NS_INLINE _Dst NS::Object::bridgingCast(const void* pObj)
{
#if __OBJC__
return (__bridge _Dst)pObj;
#else
return (_Dst)pObj;
#endif // __OBJC__
}
template <typename _Type>
_NS_INLINE constexpr bool NS::Object::doesRequireMsgSendStret()
{
#if (defined(__i386__) || defined(__x86_64__))
constexpr size_t kStructLimit = (sizeof(std::uintptr_t) << 1);
return sizeof(_Type) > kStructLimit;
#elif defined(__arm64__)
return false;
#elif defined(__arm__)
constexpr size_t kStructLimit = sizeof(std::uintptr_t);
return std::is_class(_Type) && (sizeof(_Type) > kStructLimit);
#else
#error "Unsupported architecture!"
#endif
}
template <>
_NS_INLINE constexpr bool NS::Object::doesRequireMsgSendStret<void>()
{
return false;
}
template <typename _Ret, typename... _Args>
_NS_INLINE _Ret NS::Object::sendMessage(const void* pObj, SEL selector, _Args... args)
{
#if (defined(__i386__) || defined(__x86_64__))
if constexpr (std::is_floating_point<_Ret>())
{
using SendMessageProcFpret = _Ret (*)(const void*, SEL, _Args...);
const SendMessageProcFpret pProc = reinterpret_cast<SendMessageProcFpret>(&objc_msgSend_fpret);
return (*pProc)(pObj, selector, args...);
}
else
#endif // ( defined( __i386__ ) || defined( __x86_64__ ) )
#if !defined(__arm64__)
if constexpr (doesRequireMsgSendStret<_Ret>())
{
using SendMessageProcStret = void (*)(_Ret*, const void*, SEL, _Args...);
const SendMessageProcStret pProc = reinterpret_cast<SendMessageProcStret>(&objc_msgSend_stret);
_Ret ret;
(*pProc)(&ret, pObj, selector, args...);
return ret;
}
else
#endif // !defined( __arm64__ )
{
using SendMessageProc = _Ret (*)(const void*, SEL, _Args...);
const SendMessageProc pProc = reinterpret_cast<SendMessageProc>(&objc_msgSend);
return (*pProc)(pObj, selector, args...);
}
}
_NS_INLINE NS::MethodSignature* NS::Object::methodSignatureForSelector(const void* pObj, SEL selector)
{
return sendMessage<MethodSignature*>(pObj, _NS_PRIVATE_SEL(methodSignatureForSelector_), selector);
}
_NS_INLINE bool NS::Object::respondsToSelector(const void* pObj, SEL selector)
{
return sendMessage<bool>(pObj, _NS_PRIVATE_SEL(respondsToSelector_), selector);
}
template <typename _Ret, typename... _Args>
_NS_INLINE _Ret NS::Object::sendMessageSafe(const void* pObj, SEL selector, _Args... args)
{
if ((respondsToSelector(pObj, selector)) || (nullptr != methodSignatureForSelector(pObj, selector)))
{
return sendMessage<_Ret>(pObj, selector, args...);
}
if constexpr (!std::is_void<_Ret>::value)
{
return 0;
}
}
template <class _Class>
_NS_INLINE _Class* NS::Object::alloc(const char* pClassName)
{
return sendMessage<_Class*>(objc_lookUpClass(pClassName), _NS_PRIVATE_SEL(alloc));
}
template <class _Class>
_NS_INLINE _Class* NS::Object::alloc(const void* pClass)
{
return sendMessage<_Class*>(pClass, _NS_PRIVATE_SEL(alloc));
}
template <class _Class>
_NS_INLINE _Class* NS::Object::init()
{
return sendMessage<_Class*>(this, _NS_PRIVATE_SEL(init));
}
_NS_INLINE NS::UInteger NS::Object::hash() const
{
return sendMessage<UInteger>(this, _NS_PRIVATE_SEL(hash));
}
_NS_INLINE bool NS::Object::isEqual(const Object* pObject) const
{
return sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqual_), pObject);
}
_NS_INLINE NS::String* NS::Object::description() const
{
return sendMessage<String*>(this, _NS_PRIVATE_SEL(description));
}
_NS_INLINE NS::String* NS::Object::debugDescription() const
{
return sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(debugDescription));
}
namespace NS
{
class Array : public Copying<Array>
{
public:
static Array* array();
static Array* array(const Object* pObject);
static Array* array(const Object* const* pObjects, UInteger count);
static Array* alloc();
Array* init();
Array* init(const Object* const* pObjects, UInteger count);
Array* init(const class Coder* pCoder);
template <class _Object = Object>
_Object* object(UInteger index) const;
UInteger count() const;
};
}
_NS_INLINE NS::Array* NS::Array::array()
{
return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(array));
}
_NS_INLINE NS::Array* NS::Array::array(const Object* pObject)
{
return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(arrayWithObject_), pObject);
}
_NS_INLINE NS::Array* NS::Array::array(const Object* const* pObjects, UInteger count)
{
return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(arrayWithObjects_count_), pObjects, count);
}
_NS_INLINE NS::Array* NS::Array::alloc()
{
return NS::Object::alloc<Array>(_NS_PRIVATE_CLS(NSArray));
}
_NS_INLINE NS::Array* NS::Array::init()
{
return NS::Object::init<Array>();
}
_NS_INLINE NS::Array* NS::Array::init(const Object* const* pObjects, UInteger count)
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(initWithObjects_count_), pObjects, count);
}
_NS_INLINE NS::Array* NS::Array::init(const class Coder* pCoder)
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder);
}
_NS_INLINE NS::UInteger NS::Array::count() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(count));
}
template <class _Object>
_NS_INLINE _Object* NS::Array::object(UInteger index) const
{
return Object::sendMessage<_Object*>(this, _NS_PRIVATE_SEL(objectAtIndex_), index);
}
namespace NS
{
class AutoreleasePool : public Object
{
public:
static AutoreleasePool* alloc();
AutoreleasePool* init();
void drain();
void addObject(Object* pObject);
static void showPools();
};
}
_NS_INLINE NS::AutoreleasePool* NS::AutoreleasePool::alloc()
{
return NS::Object::alloc<AutoreleasePool>(_NS_PRIVATE_CLS(NSAutoreleasePool));
}
_NS_INLINE NS::AutoreleasePool* NS::AutoreleasePool::init()
{
return NS::Object::init<AutoreleasePool>();
}
_NS_INLINE void NS::AutoreleasePool::drain()
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(drain));
}
_NS_INLINE void NS::AutoreleasePool::addObject(Object* pObject)
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(addObject_), pObject);
}
_NS_INLINE void NS::AutoreleasePool::showPools()
{
Object::sendMessage<void>(_NS_PRIVATE_CLS(NSAutoreleasePool), _NS_PRIVATE_SEL(showPools));
}
namespace NS
{
struct FastEnumerationState
{
unsigned long state;
Object** itemsPtr;
unsigned long* mutationsPtr;
unsigned long extra[5];
} _NS_PACKED;
class FastEnumeration : public Referencing<FastEnumeration>
{
public:
NS::UInteger countByEnumerating(FastEnumerationState* pState, Object** pBuffer, NS::UInteger len);
};
template <class _ObjectType>
class Enumerator : public Referencing<Enumerator<_ObjectType>, FastEnumeration>
{
public:
_ObjectType* nextObject();
class Array* allObjects();
};
}
_NS_INLINE NS::UInteger NS::FastEnumeration::countByEnumerating(FastEnumerationState* pState, Object** pBuffer, NS::UInteger len)
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(countByEnumeratingWithState_objects_count_), pState, pBuffer, len);
}
template <class _ObjectType>
_NS_INLINE _ObjectType* NS::Enumerator<_ObjectType>::nextObject()
{
return Object::sendMessage<_ObjectType*>(this, _NS_PRIVATE_SEL(nextObject));
}
template <class _ObjectType>
_NS_INLINE NS::Array* NS::Enumerator<_ObjectType>::allObjects()
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allObjects));
}
namespace NS
{
class Dictionary : public NS::Copying<Dictionary>
{
public:
static Dictionary* dictionary();
static Dictionary* dictionary(const Object* pObject, const Object* pKey);
static Dictionary* dictionary(const Object* const* pObjects, const Object* const* pKeys, UInteger count);
static Dictionary* alloc();
Dictionary* init();
Dictionary* init(const Object* const* pObjects, const Object* const* pKeys, UInteger count);
Dictionary* init(const class Coder* pCoder);
template <class _KeyType = Object>
Enumerator<_KeyType>* keyEnumerator() const;
template <class _Object = Object>
_Object* object(const Object* pKey) const;
UInteger count() const;
};
}
_NS_INLINE NS::Dictionary* NS::Dictionary::dictionary()
{
return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionary));
}
_NS_INLINE NS::Dictionary* NS::Dictionary::dictionary(const Object* pObject, const Object* pKey)
{
return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionaryWithObject_forKey_), pObject, pKey);
}
_NS_INLINE NS::Dictionary* NS::Dictionary::dictionary(const Object* const* pObjects, const Object* const* pKeys, UInteger count)
{
return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionaryWithObjects_forKeys_count_),
pObjects, pKeys, count);
}
_NS_INLINE NS::Dictionary* NS::Dictionary::alloc()
{
return NS::Object::alloc<Dictionary>(_NS_PRIVATE_CLS(NSDictionary));
}
_NS_INLINE NS::Dictionary* NS::Dictionary::init()
{
return NS::Object::init<Dictionary>();
}
_NS_INLINE NS::Dictionary* NS::Dictionary::init(const Object* const* pObjects, const Object* const* pKeys, UInteger count)
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(initWithObjects_forKeys_count_), pObjects, pKeys, count);
}
_NS_INLINE NS::Dictionary* NS::Dictionary::init(const class Coder* pCoder)
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder);
}
template <class _KeyType>
_NS_INLINE NS::Enumerator<_KeyType>* NS::Dictionary::keyEnumerator() const
{
return Object::sendMessage<Enumerator<_KeyType>*>(this, _NS_PRIVATE_SEL(keyEnumerator));
}
template <class _Object>
_NS_INLINE _Object* NS::Dictionary::object(const Object* pKey) const
{
return Object::sendMessage<_Object*>(this, _NS_PRIVATE_SEL(objectForKey_), pKey);
}
_NS_INLINE NS::UInteger NS::Dictionary::count() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(count));
}
namespace NS
{
struct Range
{
static Range Make(UInteger loc, UInteger len);
Range(UInteger loc, UInteger len);
bool Equal(const Range& range) const;
bool LocationInRange(UInteger loc) const;
UInteger Max() const;
UInteger location;
UInteger length;
} _NS_PACKED;
}
_NS_INLINE NS::Range::Range(UInteger loc, UInteger len)
: location(loc)
, length(len)
{
}
_NS_INLINE NS::Range NS::Range::Make(UInteger loc, UInteger len)
{
return Range(loc, len);
}
_NS_INLINE bool NS::Range::Equal(const Range& range) const
{
return (location == range.location) && (length == range.length);
}
_NS_INLINE bool NS::Range::LocationInRange(UInteger loc) const
{
return (!(loc < location)) && ((loc - location) < length);
}
_NS_INLINE NS::UInteger NS::Range::Max() const
{
return location + length;
}
namespace NS
{
_NS_ENUM(NS::UInteger, StringEncoding) {
ASCIIStringEncoding = 1,
NEXTSTEPStringEncoding = 2,
JapaneseEUCStringEncoding = 3,
UTF8StringEncoding = 4,
ISOLatin1StringEncoding = 5,
SymbolStringEncoding = 6,
NonLossyASCIIStringEncoding = 7,
ShiftJISStringEncoding = 8,
ISOLatin2StringEncoding = 9,
UnicodeStringEncoding = 10,
WindowsCP1251StringEncoding = 11,
WindowsCP1252StringEncoding = 12,
WindowsCP1253StringEncoding = 13,
WindowsCP1254StringEncoding = 14,
WindowsCP1250StringEncoding = 15,
ISO2022JPStringEncoding = 21,
MacOSRomanStringEncoding = 30,
UTF16StringEncoding = UnicodeStringEncoding,
UTF16BigEndianStringEncoding = 0x90000100,
UTF16LittleEndianStringEncoding = 0x94000100,
UTF32StringEncoding = 0x8c000100,
UTF32BigEndianStringEncoding = 0x98000100,
UTF32LittleEndianStringEncoding = 0x9c000100
};
_NS_OPTIONS(NS::UInteger, StringCompareOptions) {
CaseInsensitiveSearch = 1,
LiteralSearch = 2,
BackwardsSearch = 4,
AnchoredSearch = 8,
NumericSearch = 64,
DiacriticInsensitiveSearch = 128,
WidthInsensitiveSearch = 256,
ForcedOrderingSearch = 512,
RegularExpressionSearch = 1024
};
using unichar = unsigned short;
class String : public Copying<String>
{
public:
static String* string();
static String* string(const String* pString);
static String* string(const char* pString, StringEncoding encoding);
static String* alloc();
String* init();
String* init(const String* pString);
String* init(const char* pString, StringEncoding encoding);
String* init(void* pBytes, UInteger len, StringEncoding encoding, bool freeBuffer);
unichar character(UInteger index) const;
UInteger length() const;
const char* cString(StringEncoding encoding) const;
const char* utf8String() const;
UInteger maximumLengthOfBytes(StringEncoding encoding) const;
UInteger lengthOfBytes(StringEncoding encoding) const;
bool isEqualToString(const String* pString) const;
Range rangeOfString(const String* pString, StringCompareOptions options) const;
const char* fileSystemRepresentation() const;
String* stringByAppendingString(const String* pString) const;
};
template< std::size_t _StringLen >
constexpr const String* MakeConstantString( const char ( &str )[_StringLen] )
{
return reinterpret_cast< const String* >( __CFStringMakeConstantString( str ) );
}
}
_NS_INLINE NS::String* NS::String::string()
{
return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(string));
}
_NS_INLINE NS::String* NS::String::string(const String* pString)
{
return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(stringWithString_), pString);
}
_NS_INLINE NS::String* NS::String::string(const char* pString, StringEncoding encoding)
{
return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(stringWithCString_encoding_), pString, encoding);
}
_NS_INLINE NS::String* NS::String::alloc()
{
return Object::alloc<String>(_NS_PRIVATE_CLS(NSString));
}
_NS_INLINE NS::String* NS::String::init()
{
return Object::init<String>();
}
_NS_INLINE NS::String* NS::String::init(const String* pString)
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithString_), pString);
}
_NS_INLINE NS::String* NS::String::init(const char* pString, StringEncoding encoding)
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithCString_encoding_), pString, encoding);
}
_NS_INLINE NS::String* NS::String::init(void* pBytes, UInteger len, StringEncoding encoding, bool freeBuffer)
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithBytesNoCopy_length_encoding_freeWhenDone_), pBytes, len, encoding, freeBuffer);
}
_NS_INLINE NS::unichar NS::String::character(UInteger index) const
{
return Object::sendMessage<unichar>(this, _NS_PRIVATE_SEL(characterAtIndex_), index);
}
_NS_INLINE NS::UInteger NS::String::length() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(length));
}
_NS_INLINE const char* NS::String::cString(StringEncoding encoding) const
{
return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(cStringUsingEncoding_), encoding);
}
_NS_INLINE const char* NS::String::utf8String() const
{
return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(UTF8String));
}
_NS_INLINE NS::UInteger NS::String::maximumLengthOfBytes(StringEncoding encoding) const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(maximumLengthOfBytesUsingEncoding_), encoding);
}
_NS_INLINE NS::UInteger NS::String::lengthOfBytes(StringEncoding encoding) const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(lengthOfBytesUsingEncoding_), encoding);
}
_NS_INLINE bool NS::String::isEqualToString(const NS::String* pString) const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToString_), pString);
}
_NS_INLINE NS::Range NS::String::rangeOfString(const NS::String* pString, NS::StringCompareOptions options) const
{
return Object::sendMessage<Range>(this, _NS_PRIVATE_SEL(rangeOfString_options_), pString, options);
}
_NS_INLINE const char* NS::String::fileSystemRepresentation() const
{
return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(fileSystemRepresentation));
}
_NS_INLINE NS::String* NS::String::stringByAppendingString(const String* pString) const
{
return Object::sendMessage<NS::String*>(this, _NS_PRIVATE_SEL(stringByAppendingString_), pString);
}
namespace NS
{
using NotificationName = class String*;
class Notification : public NS::Referencing<Notification>
{
public:
NS::String* name() const;
NS::Object* object() const;
NS::Dictionary* userInfo() const;
};
}
_NS_INLINE NS::String* NS::Notification::name() const
{
return Object::sendMessage<NS::String*>(this, _NS_PRIVATE_SEL(name));
}
_NS_INLINE NS::Object* NS::Notification::object() const
{
return Object::sendMessage<NS::Object*>(this, _NS_PRIVATE_SEL(object));
}
_NS_INLINE NS::Dictionary* NS::Notification::userInfo() const
{
return Object::sendMessage<NS::Dictionary*>(this, _NS_PRIVATE_SEL(userInfo));
}
namespace NS
{
_NS_CONST(NotificationName, BundleDidLoadNotification);
_NS_CONST(NotificationName, BundleResourceRequestLowDiskSpaceNotification);
class String* LocalizedString(const String* pKey, const String*);
class String* LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*);
class String* LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const class Bundle* pBdle, const String*);
class String* LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const class Bundle* pBdle, const String* pVal, const String*);
class Bundle : public Referencing<Bundle>
{
public:
static Bundle* mainBundle();
static Bundle* bundle(const class String* pPath);
static Bundle* bundle(const class URL* pURL);
static Bundle* alloc();
Bundle* init(const class String* pPath);
Bundle* init(const class URL* pURL);
class Array* allBundles() const;
class Array* allFrameworks() const;
bool load();
bool unload();
bool isLoaded() const;
bool preflightAndReturnError(class Error** pError) const;
bool loadAndReturnError(class Error** pError);
class URL* bundleURL() const;
class URL* resourceURL() const;
class URL* executableURL() const;
class URL* URLForAuxiliaryExecutable(const class String* pExecutableName) const;
class URL* privateFrameworksURL() const;
class URL* sharedFrameworksURL() const;
class URL* sharedSupportURL() const;
class URL* builtInPlugInsURL() const;
class URL* appStoreReceiptURL() const;
class String* bundlePath() const;
class String* resourcePath() const;
class String* executablePath() const;
class String* pathForAuxiliaryExecutable(const class String* pExecutableName) const;
class String* privateFrameworksPath() const;
class String* sharedFrameworksPath() const;
class String* sharedSupportPath() const;
class String* builtInPlugInsPath() const;
class String* bundleIdentifier() const;
class Dictionary* infoDictionary() const;
class Dictionary* localizedInfoDictionary() const;
class Object* objectForInfoDictionaryKey(const class String* pKey);
class String* localizedString(const class String* pKey, const class String* pValue = nullptr, const class String* pTableName = nullptr) const;
};
}
_NS_PRIVATE_DEF_CONST(NS::NotificationName, BundleDidLoadNotification);
_NS_PRIVATE_DEF_CONST(NS::NotificationName, BundleResourceRequestLowDiskSpaceNotification);
_NS_INLINE NS::String* NS::LocalizedString(const String* pKey, const String*)
{
return Bundle::mainBundle()->localizedString(pKey, nullptr, nullptr);
}
_NS_INLINE NS::String* NS::LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*)
{
return Bundle::mainBundle()->localizedString(pKey, nullptr, pTbl);
}
_NS_INLINE NS::String* NS::LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const Bundle* pBdl, const String*)
{
return pBdl->localizedString(pKey, nullptr, pTbl);
}
_NS_INLINE NS::String* NS::LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const Bundle* pBdl, const String* pVal, const String*)
{
return pBdl->localizedString(pKey, pVal, pTbl);
}
_NS_INLINE NS::Bundle* NS::Bundle::mainBundle()
{
return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(mainBundle));
}
_NS_INLINE NS::Bundle* NS::Bundle::bundle(const class String* pPath)
{
return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(bundleWithPath_), pPath);
}
_NS_INLINE NS::Bundle* NS::Bundle::bundle(const class URL* pURL)
{
return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(bundleWithURL_), pURL);
}
_NS_INLINE NS::Bundle* NS::Bundle::alloc()
{
return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(alloc));
}
_NS_INLINE NS::Bundle* NS::Bundle::init(const String* pPath)
{
return Object::sendMessage<Bundle*>(this, _NS_PRIVATE_SEL(initWithPath_), pPath);
}
_NS_INLINE NS::Bundle* NS::Bundle::init(const URL* pURL)
{
return Object::sendMessage<Bundle*>(this, _NS_PRIVATE_SEL(initWithURL_), pURL);
}
_NS_INLINE NS::Array* NS::Bundle::allBundles() const
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allBundles));
}
_NS_INLINE NS::Array* NS::Bundle::allFrameworks() const
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allFrameworks));
}
_NS_INLINE bool NS::Bundle::load()
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(load));
}
_NS_INLINE bool NS::Bundle::unload()
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(unload));
}
_NS_INLINE bool NS::Bundle::isLoaded() const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isLoaded));
}
_NS_INLINE bool NS::Bundle::preflightAndReturnError(Error** pError) const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(preflightAndReturnError_), pError);
}
_NS_INLINE bool NS::Bundle::loadAndReturnError(Error** pError)
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(loadAndReturnError_), pError);
}
_NS_INLINE NS::URL* NS::Bundle::bundleURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(bundleURL));
}
_NS_INLINE NS::URL* NS::Bundle::resourceURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(resourceURL));
}
_NS_INLINE NS::URL* NS::Bundle::executableURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(executableURL));
}
_NS_INLINE NS::URL* NS::Bundle::URLForAuxiliaryExecutable(const String* pExecutableName) const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(URLForAuxiliaryExecutable_), pExecutableName);
}
_NS_INLINE NS::URL* NS::Bundle::privateFrameworksURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(privateFrameworksURL));
}
_NS_INLINE NS::URL* NS::Bundle::sharedFrameworksURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(sharedFrameworksURL));
}
_NS_INLINE NS::URL* NS::Bundle::sharedSupportURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(sharedSupportURL));
}
_NS_INLINE NS::URL* NS::Bundle::builtInPlugInsURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(builtInPlugInsURL));
}
_NS_INLINE NS::URL* NS::Bundle::appStoreReceiptURL() const
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(appStoreReceiptURL));
}
_NS_INLINE NS::String* NS::Bundle::bundlePath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(bundlePath));
}
_NS_INLINE NS::String* NS::Bundle::resourcePath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(resourcePath));
}
_NS_INLINE NS::String* NS::Bundle::executablePath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(executablePath));
}
_NS_INLINE NS::String* NS::Bundle::pathForAuxiliaryExecutable(const String* pExecutableName) const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(pathForAuxiliaryExecutable_), pExecutableName);
}
_NS_INLINE NS::String* NS::Bundle::privateFrameworksPath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(privateFrameworksPath));
}
_NS_INLINE NS::String* NS::Bundle::sharedFrameworksPath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(sharedFrameworksPath));
}
_NS_INLINE NS::String* NS::Bundle::sharedSupportPath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(sharedSupportPath));
}
_NS_INLINE NS::String* NS::Bundle::builtInPlugInsPath() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(builtInPlugInsPath));
}
_NS_INLINE NS::String* NS::Bundle::bundleIdentifier() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(bundleIdentifier));
}
_NS_INLINE NS::Dictionary* NS::Bundle::infoDictionary() const
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(infoDictionary));
}
_NS_INLINE NS::Dictionary* NS::Bundle::localizedInfoDictionary() const
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(localizedInfoDictionary));
}
_NS_INLINE NS::Object* NS::Bundle::objectForInfoDictionaryKey(const String* pKey)
{
return Object::sendMessage<Object*>(this, _NS_PRIVATE_SEL(objectForInfoDictionaryKey_), pKey);
}
_NS_INLINE NS::String* NS::Bundle::localizedString(const String* pKey, const String* pValue /* = nullptr */, const String* pTableName /* = nullptr */) const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedStringForKey_value_table_), pKey, pValue, pTableName);
}
namespace NS
{
class Data : public Copying<Data>
{
public:
void* mutableBytes() const;
UInteger length() const;
};
}
_NS_INLINE void* NS::Data::mutableBytes() const
{
return Object::sendMessage<void*>(this, _NS_PRIVATE_SEL(mutableBytes));
}
_NS_INLINE NS::UInteger NS::Data::length() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(length));
}
namespace NS
{
using TimeInterval = double;
class Date : public Copying<Date>
{
public:
static Date* dateWithTimeIntervalSinceNow(TimeInterval secs);
};
} // NS
_NS_INLINE NS::Date* NS::Date::dateWithTimeIntervalSinceNow(NS::TimeInterval secs)
{
return NS::Object::sendMessage<NS::Date*>(_NS_PRIVATE_CLS(NSDate), _NS_PRIVATE_SEL(dateWithTimeIntervalSinceNow_), secs);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace NS
{
using ErrorDomain = class String*;
_NS_CONST(ErrorDomain, CocoaErrorDomain);
_NS_CONST(ErrorDomain, POSIXErrorDomain);
_NS_CONST(ErrorDomain, OSStatusErrorDomain);
_NS_CONST(ErrorDomain, MachErrorDomain);
using ErrorUserInfoKey = class String*;
_NS_CONST(ErrorUserInfoKey, UnderlyingErrorKey);
_NS_CONST(ErrorUserInfoKey, LocalizedDescriptionKey);
_NS_CONST(ErrorUserInfoKey, LocalizedFailureReasonErrorKey);
_NS_CONST(ErrorUserInfoKey, LocalizedRecoverySuggestionErrorKey);
_NS_CONST(ErrorUserInfoKey, LocalizedRecoveryOptionsErrorKey);
_NS_CONST(ErrorUserInfoKey, RecoveryAttempterErrorKey);
_NS_CONST(ErrorUserInfoKey, HelpAnchorErrorKey);
_NS_CONST(ErrorUserInfoKey, DebugDescriptionErrorKey);
_NS_CONST(ErrorUserInfoKey, LocalizedFailureErrorKey);
_NS_CONST(ErrorUserInfoKey, StringEncodingErrorKey);
_NS_CONST(ErrorUserInfoKey, URLErrorKey);
_NS_CONST(ErrorUserInfoKey, FilePathErrorKey);
class Error : public Copying<Error>
{
public:
static Error* error(ErrorDomain domain, Integer code, class Dictionary* pDictionary);
static Error* alloc();
Error* init();
Error* init(ErrorDomain domain, Integer code, class Dictionary* pDictionary);
Integer code() const;
ErrorDomain domain() const;
class Dictionary* userInfo() const;
class String* localizedDescription() const;
class Array* localizedRecoveryOptions() const;
class String* localizedRecoverySuggestion() const;
class String* localizedFailureReason() const;
};
}
_NS_PRIVATE_DEF_CONST(NS::ErrorDomain, CocoaErrorDomain);
_NS_PRIVATE_DEF_CONST(NS::ErrorDomain, POSIXErrorDomain);
_NS_PRIVATE_DEF_CONST(NS::ErrorDomain, OSStatusErrorDomain);
_NS_PRIVATE_DEF_CONST(NS::ErrorDomain, MachErrorDomain);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, UnderlyingErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedDescriptionKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedFailureReasonErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedRecoverySuggestionErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedRecoveryOptionsErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, RecoveryAttempterErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, HelpAnchorErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, DebugDescriptionErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedFailureErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, StringEncodingErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, URLErrorKey);
_NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, FilePathErrorKey);
_NS_INLINE NS::Error* NS::Error::error(ErrorDomain domain, Integer code, class Dictionary* pDictionary)
{
return Object::sendMessage<Error*>(_NS_PRIVATE_CLS(NSError), _NS_PRIVATE_SEL(errorWithDomain_code_userInfo_), domain, code, pDictionary);
}
_NS_INLINE NS::Error* NS::Error::alloc()
{
return Object::alloc<Error>(_NS_PRIVATE_CLS(NSError));
}
_NS_INLINE NS::Error* NS::Error::init()
{
return Object::init<Error>();
}
_NS_INLINE NS::Error* NS::Error::init(ErrorDomain domain, Integer code, class Dictionary* pDictionary)
{
return Object::sendMessage<Error*>(this, _NS_PRIVATE_SEL(initWithDomain_code_userInfo_), domain, code, pDictionary);
}
_NS_INLINE NS::Integer NS::Error::code() const
{
return Object::sendMessage<Integer>(this, _NS_PRIVATE_SEL(code));
}
_NS_INLINE NS::ErrorDomain NS::Error::domain() const
{
return Object::sendMessage<ErrorDomain>(this, _NS_PRIVATE_SEL(domain));
}
_NS_INLINE NS::Dictionary* NS::Error::userInfo() const
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(userInfo));
}
_NS_INLINE NS::String* NS::Error::localizedDescription() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedDescription));
}
_NS_INLINE NS::Array* NS::Error::localizedRecoveryOptions() const
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(localizedRecoveryOptions));
}
_NS_INLINE NS::String* NS::Error::localizedRecoverySuggestion() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedRecoverySuggestion));
}
_NS_INLINE NS::String* NS::Error::localizedFailureReason() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedFailureReason));
}
namespace NS
{
template <class _Class, class _Base = class Object>
class Locking : public _Base
{
public:
void lock();
void unlock();
};
class Condition : public Locking<Condition>
{
public:
static Condition* alloc();
Condition* init();
void wait();
bool waitUntilDate(Date* pLimit);
void signal();
void broadcast();
};
} // NS
template<class _Class, class _Base /* = NS::Object */>
_NS_INLINE void NS::Locking<_Class, _Base>::lock()
{
NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(lock));
}
template<class _Class, class _Base /* = NS::Object */>
_NS_INLINE void NS::Locking<_Class, _Base>::unlock()
{
NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(unlock));
}
_NS_INLINE NS::Condition* NS::Condition::alloc()
{
return NS::Object::alloc<NS::Condition>(_NS_PRIVATE_CLS(NSCondition));
}
_NS_INLINE NS::Condition* NS::Condition::init()
{
return NS::Object::init<NS::Condition>();
}
_NS_INLINE void NS::Condition::wait()
{
NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(wait));
}
_NS_INLINE bool NS::Condition::waitUntilDate(NS::Date* pLimit)
{
return NS::Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(waitUntilDate_), pLimit);
}
_NS_INLINE void NS::Condition::signal()
{
NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(signal));
}
_NS_INLINE void NS::Condition::broadcast()
{
NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(broadcast));
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace NS
{
_NS_ENUM(Integer, ComparisonResult) {
OrderedAscending = -1,
OrderedSame = 0,
OrderedDescending = 1,
};
const Integer NotFound = IntegerMax;
}
namespace NS
{
class Value : public Copying<Value>
{
public:
static Value* value(const void* pValue, const char* pType);
static Value* value(const void* pPointer);
static Value* alloc();
Value* init(const void* pValue, const char* pType);
Value* init(const class Coder* pCoder);
void getValue(void* pValue, UInteger size) const;
const char* objCType() const;
bool isEqualToValue(Value* pValue) const;
void* pointerValue() const;
};
class Number : public Copying<Number, Value>
{
public:
static Number* number(char value);
static Number* number(unsigned char value);
static Number* number(short value);
static Number* number(unsigned short value);
static Number* number(int value);
static Number* number(unsigned int value);
static Number* number(long value);
static Number* number(unsigned long value);
static Number* number(long long value);
static Number* number(unsigned long long value);
static Number* number(float value);
static Number* number(double value);
static Number* number(bool value);
static Number* alloc();
Number* init(const class Coder* pCoder);
Number* init(char value);
Number* init(unsigned char value);
Number* init(short value);
Number* init(unsigned short value);
Number* init(int value);
Number* init(unsigned int value);
Number* init(long value);
Number* init(unsigned long value);
Number* init(long long value);
Number* init(unsigned long long value);
Number* init(float value);
Number* init(double value);
Number* init(bool value);
char charValue() const;
unsigned char unsignedCharValue() const;
short shortValue() const;
unsigned short unsignedShortValue() const;
int intValue() const;
unsigned int unsignedIntValue() const;
long longValue() const;
unsigned long unsignedLongValue() const;
long long longLongValue() const;
unsigned long long unsignedLongLongValue() const;
float floatValue() const;
double doubleValue() const;
bool boolValue() const;
Integer integerValue() const;
UInteger unsignedIntegerValue() const;
class String* stringValue() const;
ComparisonResult compare(const Number* pOtherNumber) const;
bool isEqualToNumber(const Number* pNumber) const;
class String* descriptionWithLocale(const Object* pLocale) const;
};
}
_NS_INLINE NS::Value* NS::Value::value(const void* pValue, const char* pType)
{
return Object::sendMessage<Value*>(_NS_PRIVATE_CLS(NSValue), _NS_PRIVATE_SEL(valueWithBytes_objCType_), pValue, pType);
}
_NS_INLINE NS::Value* NS::Value::value(const void* pPointer)
{
return Object::sendMessage<Value*>(_NS_PRIVATE_CLS(NSValue), _NS_PRIVATE_SEL(valueWithPointer_), pPointer);
}
_NS_INLINE NS::Value* NS::Value::alloc()
{
return NS::Object::alloc<Value>(_NS_PRIVATE_CLS(NSValue));
}
_NS_INLINE NS::Value* NS::Value::init(const void* pValue, const char* pType)
{
return Object::sendMessage<Value*>(this, _NS_PRIVATE_SEL(initWithBytes_objCType_), pValue, pType);
}
_NS_INLINE NS::Value* NS::Value::init(const class Coder* pCoder)
{
return Object::sendMessage<Value*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder);
}
_NS_INLINE void NS::Value::getValue(void* pValue, UInteger size) const
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(getValue_size_), pValue, size);
}
_NS_INLINE const char* NS::Value::objCType() const
{
return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(objCType));
}
_NS_INLINE bool NS::Value::isEqualToValue(Value* pValue) const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToValue_), pValue);
}
_NS_INLINE void* NS::Value::pointerValue() const
{
return Object::sendMessage<void*>(this, _NS_PRIVATE_SEL(pointerValue));
}
_NS_INLINE NS::Number* NS::Number::number(char value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithChar_), value);
}
_NS_INLINE NS::Number* NS::Number::number(unsigned char value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedChar_), value);
}
_NS_INLINE NS::Number* NS::Number::number(short value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithShort_), value);
}
_NS_INLINE NS::Number* NS::Number::number(unsigned short value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedShort_), value);
}
_NS_INLINE NS::Number* NS::Number::number(int value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithInt_), value);
}
_NS_INLINE NS::Number* NS::Number::number(unsigned int value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedInt_), value);
}
_NS_INLINE NS::Number* NS::Number::number(long value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithLong_), value);
}
_NS_INLINE NS::Number* NS::Number::number(unsigned long value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedLong_), value);
}
_NS_INLINE NS::Number* NS::Number::number(long long value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithLongLong_), value);
}
_NS_INLINE NS::Number* NS::Number::number(unsigned long long value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedLongLong_), value);
}
_NS_INLINE NS::Number* NS::Number::number(float value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithFloat_), value);
}
_NS_INLINE NS::Number* NS::Number::number(double value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithDouble_), value);
}
_NS_INLINE NS::Number* NS::Number::number(bool value)
{
return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithBool_), value);
}
_NS_INLINE NS::Number* NS::Number::alloc()
{
return NS::Object::alloc<Number>(_NS_PRIVATE_CLS(NSNumber));
}
_NS_INLINE NS::Number* NS::Number::init(const Coder* pCoder)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder);
}
_NS_INLINE NS::Number* NS::Number::init(char value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithChar_), value);
}
_NS_INLINE NS::Number* NS::Number::init(unsigned char value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedChar_), value);
}
_NS_INLINE NS::Number* NS::Number::init(short value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithShort_), value);
}
_NS_INLINE NS::Number* NS::Number::init(unsigned short value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedShort_), value);
}
_NS_INLINE NS::Number* NS::Number::init(int value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithInt_), value);
}
_NS_INLINE NS::Number* NS::Number::init(unsigned int value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedInt_), value);
}
_NS_INLINE NS::Number* NS::Number::init(long value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithLong_), value);
}
_NS_INLINE NS::Number* NS::Number::init(unsigned long value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedLong_), value);
}
_NS_INLINE NS::Number* NS::Number::init(long long value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithLongLong_), value);
}
_NS_INLINE NS::Number* NS::Number::init(unsigned long long value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedLongLong_), value);
}
_NS_INLINE NS::Number* NS::Number::init(float value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithFloat_), value);
}
_NS_INLINE NS::Number* NS::Number::init(double value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithDouble_), value);
}
_NS_INLINE NS::Number* NS::Number::init(bool value)
{
return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithBool_), value);
}
_NS_INLINE char NS::Number::charValue() const
{
return Object::sendMessage<char>(this, _NS_PRIVATE_SEL(charValue));
}
_NS_INLINE unsigned char NS::Number::unsignedCharValue() const
{
return Object::sendMessage<unsigned char>(this, _NS_PRIVATE_SEL(unsignedCharValue));
}
_NS_INLINE short NS::Number::shortValue() const
{
return Object::sendMessage<short>(this, _NS_PRIVATE_SEL(shortValue));
}
_NS_INLINE unsigned short NS::Number::unsignedShortValue() const
{
return Object::sendMessage<unsigned short>(this, _NS_PRIVATE_SEL(unsignedShortValue));
}
_NS_INLINE int NS::Number::intValue() const
{
return Object::sendMessage<int>(this, _NS_PRIVATE_SEL(intValue));
}
_NS_INLINE unsigned int NS::Number::unsignedIntValue() const
{
return Object::sendMessage<unsigned int>(this, _NS_PRIVATE_SEL(unsignedIntValue));
}
_NS_INLINE long NS::Number::longValue() const
{
return Object::sendMessage<long>(this, _NS_PRIVATE_SEL(longValue));
}
_NS_INLINE unsigned long NS::Number::unsignedLongValue() const
{
return Object::sendMessage<unsigned long>(this, _NS_PRIVATE_SEL(unsignedLongValue));
}
_NS_INLINE long long NS::Number::longLongValue() const
{
return Object::sendMessage<long long>(this, _NS_PRIVATE_SEL(longLongValue));
}
_NS_INLINE unsigned long long NS::Number::unsignedLongLongValue() const
{
return Object::sendMessage<unsigned long long>(this, _NS_PRIVATE_SEL(unsignedLongLongValue));
}
_NS_INLINE float NS::Number::floatValue() const
{
return Object::sendMessage<float>(this, _NS_PRIVATE_SEL(floatValue));
}
_NS_INLINE double NS::Number::doubleValue() const
{
return Object::sendMessage<double>(this, _NS_PRIVATE_SEL(doubleValue));
}
_NS_INLINE bool NS::Number::boolValue() const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(boolValue));
}
_NS_INLINE NS::Integer NS::Number::integerValue() const
{
return Object::sendMessage<Integer>(this, _NS_PRIVATE_SEL(integerValue));
}
_NS_INLINE NS::UInteger NS::Number::unsignedIntegerValue() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(unsignedIntegerValue));
}
_NS_INLINE NS::String* NS::Number::stringValue() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(stringValue));
}
_NS_INLINE NS::ComparisonResult NS::Number::compare(const Number* pOtherNumber) const
{
return Object::sendMessage<ComparisonResult>(this, _NS_PRIVATE_SEL(compare_), pOtherNumber);
}
_NS_INLINE bool NS::Number::isEqualToNumber(const Number* pNumber) const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToNumber_), pNumber);
}
_NS_INLINE NS::String* NS::Number::descriptionWithLocale(const Object* pLocale) const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(descriptionWithLocale_), pLocale);
}
#include <functional>
namespace NS
{
_NS_CONST(NotificationName, ProcessInfoThermalStateDidChangeNotification);
_NS_CONST(NotificationName, ProcessInfoPowerStateDidChangeNotification);
_NS_ENUM(NS::Integer, ProcessInfoThermalState) {
ProcessInfoThermalStateNominal = 0,
ProcessInfoThermalStateFair = 1,
ProcessInfoThermalStateSerious = 2,
ProcessInfoThermalStateCritical = 3
};
_NS_OPTIONS(std::uint64_t, ActivityOptions) {
ActivityIdleDisplaySleepDisabled = (1ULL << 40),
ActivityIdleSystemSleepDisabled = (1ULL << 20),
ActivitySuddenTerminationDisabled = (1ULL << 14),
ActivityAutomaticTerminationDisabled = (1ULL << 15),
ActivityUserInitiated = (0x00FFFFFFULL | ActivityIdleSystemSleepDisabled),
ActivityUserInitiatedAllowingIdleSystemSleep = (ActivityUserInitiated & ~ActivityIdleSystemSleepDisabled),
ActivityBackground = 0x000000FFULL,
ActivityLatencyCritical = 0xFF00000000ULL,
};
class ProcessInfo : public Referencing<ProcessInfo>
{
public:
static ProcessInfo* processInfo();
class Array* arguments() const;
class Dictionary* environment() const;
class String* hostName() const;
class String* processName() const;
void setProcessName(const String* pString);
int processIdentifier() const;
class String* globallyUniqueString() const;
class String* userName() const;
class String* fullUserName() const;
UInteger operatingSystem() const;
OperatingSystemVersion operatingSystemVersion() const;
class String* operatingSystemVersionString() const;
bool isOperatingSystemAtLeastVersion(OperatingSystemVersion version) const;
UInteger processorCount() const;
UInteger activeProcessorCount() const;
unsigned long long physicalMemory() const;
TimeInterval systemUptime() const;
void disableSuddenTermination();
void enableSuddenTermination();
void disableAutomaticTermination(const class String* pReason);
void enableAutomaticTermination(const class String* pReason);
bool automaticTerminationSupportEnabled() const;
void setAutomaticTerminationSupportEnabled(bool enabled);
class Object* beginActivity(ActivityOptions options, const class String* pReason);
void endActivity(class Object* pActivity);
void performActivity(ActivityOptions options, const class String* pReason, void (^block)(void));
void performActivity(ActivityOptions options, const class String* pReason, const std::function<void()>& func);
void performExpiringActivity(const class String* pReason, void (^block)(bool expired));
void performExpiringActivity(const class String* pReason, const std::function<void(bool expired)>& func);
ProcessInfoThermalState thermalState() const;
bool isLowPowerModeEnabled() const;
bool isiOSAppOnMac() const;
bool isMacCatalystApp() const;
};
}
_NS_PRIVATE_DEF_CONST(NS::NotificationName, ProcessInfoThermalStateDidChangeNotification);
_NS_PRIVATE_DEF_CONST(NS::NotificationName, ProcessInfoPowerStateDidChangeNotification);
_NS_INLINE NS::ProcessInfo* NS::ProcessInfo::processInfo()
{
return Object::sendMessage<ProcessInfo*>(_NS_PRIVATE_CLS(NSProcessInfo), _NS_PRIVATE_SEL(processInfo));
}
_NS_INLINE NS::Array* NS::ProcessInfo::arguments() const
{
return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(arguments));
}
_NS_INLINE NS::Dictionary* NS::ProcessInfo::environment() const
{
return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(environment));
}
_NS_INLINE NS::String* NS::ProcessInfo::hostName() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(hostName));
}
_NS_INLINE NS::String* NS::ProcessInfo::processName() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(processName));
}
_NS_INLINE void NS::ProcessInfo::setProcessName(const String* pString)
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(setProcessName_), pString);
}
_NS_INLINE int NS::ProcessInfo::processIdentifier() const
{
return Object::sendMessage<int>(this, _NS_PRIVATE_SEL(processIdentifier));
}
_NS_INLINE NS::String* NS::ProcessInfo::globallyUniqueString() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(globallyUniqueString));
}
_NS_INLINE NS::String* NS::ProcessInfo::userName() const
{
return Object::sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(userName));
}
_NS_INLINE NS::String* NS::ProcessInfo::fullUserName() const
{
return Object::sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(fullUserName));
}
_NS_INLINE NS::UInteger NS::ProcessInfo::operatingSystem() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(operatingSystem));
}
_NS_INLINE NS::OperatingSystemVersion NS::ProcessInfo::operatingSystemVersion() const
{
return Object::sendMessage<OperatingSystemVersion>(this, _NS_PRIVATE_SEL(operatingSystemVersion));
}
_NS_INLINE NS::String* NS::ProcessInfo::operatingSystemVersionString() const
{
return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(operatingSystemVersionString));
}
_NS_INLINE bool NS::ProcessInfo::isOperatingSystemAtLeastVersion(OperatingSystemVersion version) const
{
return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isOperatingSystemAtLeastVersion_), version);
}
_NS_INLINE NS::UInteger NS::ProcessInfo::processorCount() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(processorCount));
}
_NS_INLINE NS::UInteger NS::ProcessInfo::activeProcessorCount() const
{
return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(activeProcessorCount));
}
_NS_INLINE unsigned long long NS::ProcessInfo::physicalMemory() const
{
return Object::sendMessage<unsigned long long>(this, _NS_PRIVATE_SEL(physicalMemory));
}
_NS_INLINE NS::TimeInterval NS::ProcessInfo::systemUptime() const
{
return Object::sendMessage<TimeInterval>(this, _NS_PRIVATE_SEL(systemUptime));
}
_NS_INLINE void NS::ProcessInfo::disableSuddenTermination()
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(disableSuddenTermination));
}
_NS_INLINE void NS::ProcessInfo::enableSuddenTermination()
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(enableSuddenTermination));
}
_NS_INLINE void NS::ProcessInfo::disableAutomaticTermination(const String* pReason)
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(disableAutomaticTermination_), pReason);
}
_NS_INLINE void NS::ProcessInfo::enableAutomaticTermination(const String* pReason)
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(enableAutomaticTermination_), pReason);
}
_NS_INLINE bool NS::ProcessInfo::automaticTerminationSupportEnabled() const
{
return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(automaticTerminationSupportEnabled));
}
_NS_INLINE void NS::ProcessInfo::setAutomaticTerminationSupportEnabled(bool enabled)
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(setAutomaticTerminationSupportEnabled_), enabled);
}
_NS_INLINE NS::Object* NS::ProcessInfo::beginActivity(ActivityOptions options, const String* pReason)
{
return Object::sendMessage<Object*>(this, _NS_PRIVATE_SEL(beginActivityWithOptions_reason_), options, pReason);
}
_NS_INLINE void NS::ProcessInfo::endActivity(Object* pActivity)
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(endActivity_), pActivity);
}
_NS_INLINE void NS::ProcessInfo::performActivity(ActivityOptions options, const String* pReason, void (^block)(void))
{
Object::sendMessage<void>(this, _NS_PRIVATE_SEL(performActivityWithOptions_reason_usingBlock_), options, pReason, block);
}
_NS_INLINE void NS::ProcessInfo::performActivity(ActivityOptions options, const String* pReason, const std::function<void()>& function)
{
__block std::function<void()> blockFunction = function;
performActivity(options, pReason, ^() { blockFunction(); });
}
_NS_INLINE void NS::ProcessInfo::performExpiringActivity(const String* pReason, void (^block)(bool expired))
{
Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(performExpiringActivityWithReason_usingBlock_), pReason, block);
}
_NS_INLINE void NS::ProcessInfo::performExpiringActivity(const String* pReason, const std::function<void(bool expired)>& function)
{
__block std::function<void(bool expired)> blockFunction = function;
performExpiringActivity(pReason, ^(bool expired) { blockFunction(expired); });
}
_NS_INLINE NS::ProcessInfoThermalState NS::ProcessInfo::thermalState() const
{
return Object::sendMessage<ProcessInfoThermalState>(this, _NS_PRIVATE_SEL(thermalState));
}
_NS_INLINE bool NS::ProcessInfo::isLowPowerModeEnabled() const
{
return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isLowPowerModeEnabled));
}
_NS_INLINE bool NS::ProcessInfo::isiOSAppOnMac() const
{
return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isiOSAppOnMac));
}
_NS_INLINE bool NS::ProcessInfo::isMacCatalystApp() const
{
return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isMacCatalystApp));
}
namespace NS
{
class URL : public Copying<URL>
{
public:
static URL* fileURLWithPath(const class String* pPath);
static URL* alloc();
URL* init();
URL* init(const class String* pString);
URL* initFileURLWithPath(const class String* pPath);
const char* fileSystemRepresentation() const;
};
}
_NS_INLINE NS::URL* NS::URL::fileURLWithPath(const String* pPath)
{
return Object::sendMessage<URL*>(_NS_PRIVATE_CLS(NSURL), _NS_PRIVATE_SEL(fileURLWithPath_), pPath);
}
_NS_INLINE NS::URL* NS::URL::alloc()
{
return Object::alloc<URL>(_NS_PRIVATE_CLS(NSURL));
}
_NS_INLINE NS::URL* NS::URL::init()
{
return Object::init<URL>();
}
_NS_INLINE NS::URL* NS::URL::init(const String* pString)
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(initWithString_), pString);
}
_NS_INLINE NS::URL* NS::URL::initFileURLWithPath(const String* pPath)
{
return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(initFileURLWithPath_), pPath);
}
_NS_INLINE const char* NS::URL::fileSystemRepresentation() const
{
return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(fileSystemRepresentation));
}
#pragma once
#define _MTL_EXPORT _NS_EXPORT
#define _MTL_EXTERN _NS_EXTERN
#define _MTL_INLINE _NS_INLINE
#define _MTL_PACKED _NS_PACKED
#define _MTL_CONST(type, name) _NS_CONST(type, name)
#define _MTL_ENUM(type, name) _NS_ENUM(type, name)
#define _MTL_OPTIONS(type, name) _NS_ENUM(type, name)
#define _MTL_VALIDATE_SIZE(ns, name) _NS_VALIDATE_SIZE(ns, name)
#define _MTL_VALIDATE_ENUM(ns, name) _NS_VALIDATE_ENUM(ns, name)
#pragma once
#include <objc/runtime.h>
#define _MTL_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol)
#define _MTL_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor)
#if defined(MTL_PRIVATE_IMPLEMENTATION)
#define _MTL_PRIVATE_VISIBILITY __attribute__((visibility("default")))
#define _MTL_PRIVATE_IMPORT __attribute__((weak_import))
#if __OBJC__
#define _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol))
#else
#define _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol)
#endif // __OBJC__
#define _MTL_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _MTL_PRIVATE_VISIBILITY = _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol);
#define _MTL_PRIVATE_DEF_PRO(symbol)
#define _MTL_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _MTL_PRIVATE_VISIBILITY = sel_registerName(symbol);
#if defined(__MAC_10_16) || defined(__MAC_11_0) || defined(__MAC_12_0) || defined(__IPHONE_14_0) || defined(__IPHONE_15_0) || defined(__TVOS_14_0) || defined(__TVOS_15_0)
#define _MTL_PRIVATE_DEF_STR(type, symbol) \
_MTL_EXTERN type const MTL##symbol _MTL_PRIVATE_IMPORT; \
type const MTL::symbol = (nullptr != &MTL##symbol) ? MTL##symbol : nullptr;
#else
#include <dlfcn.h>
namespace MTL
{
namespace Private
{
template <typename _Type>
inline _Type const LoadSymbol(const char* pSymbol)
{
const _Type* pAddress = static_cast<_Type*>(dlsym(RTLD_DEFAULT, pSymbol));
return pAddress ? *pAddress : nullptr;
}
} // Private
} // MTL
#define _MTL_PRIVATE_DEF_STR(type, symbol) \
_MTL_EXTERN type const MTL##symbol; \
type const MTL::symbol = Private::LoadSymbol<type>("MTL" #symbol);
#endif // defined(__MAC_10_16) || defined(__MAC_11_0) || defined(__MAC_12_0) || defined(__IPHONE_14_0) || defined(__IPHONE_15_0) || defined(__TVOS_14_0) || defined(__TVOS_15_0)
#else
#define _MTL_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol;
#define _MTL_PRIVATE_DEF_PRO(symbol)
#define _MTL_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor;
#define _MTL_PRIVATE_DEF_STR(type, symbol)
#endif // MTL_PRIVATE_IMPLEMENTATION
namespace MTL
{
namespace Private
{
namespace Class
{
} // Class
} // Private
} // MTL
namespace MTL
{
namespace Private
{
namespace Protocol
{
} // Protocol
} // Private
} // MTL
namespace MTL
{
namespace Private
{
namespace Selector
{
_MTL_PRIVATE_DEF_SEL(beginScope,
"beginScope");
_MTL_PRIVATE_DEF_SEL(endScope,
"endScope");
} // Class
} // Private
} // MTL
namespace MTL::Private::Class
{
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureGeometryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureTriangleGeometryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLArgument);
_MTL_PRIVATE_DEF_CLS(MTLArgumentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLArrayType);
_MTL_PRIVATE_DEF_CLS(MTLAttribute);
_MTL_PRIVATE_DEF_CLS(MTLAttributeDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLAttributeDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLBinaryArchiveDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLBlitPassDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLBlitPassSampleBufferAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLBlitPassSampleBufferAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLBufferLayoutDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLBufferLayoutDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLCaptureDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLCaptureManager);
_MTL_PRIVATE_DEF_CLS(MTLCommandBufferDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLCompileOptions);
_MTL_PRIVATE_DEF_CLS(MTLComputePassDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLComputePassSampleBufferAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLComputePassSampleBufferAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLComputePipelineDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLComputePipelineReflection);
_MTL_PRIVATE_DEF_CLS(MTLCounterSampleBufferDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLDepthStencilDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLFunctionConstant);
_MTL_PRIVATE_DEF_CLS(MTLFunctionConstantValues);
_MTL_PRIVATE_DEF_CLS(MTLFunctionDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingAttributeAlwaysInline);
_MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingFunctionNode);
_MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingGraph);
_MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingInputNode);
_MTL_PRIVATE_DEF_CLS(MTLHeapDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLIndirectCommandBufferDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLInstanceAccelerationStructureDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLIntersectionFunctionDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLIntersectionFunctionTableDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLLinkedFunctions);
_MTL_PRIVATE_DEF_CLS(MTLMotionKeyframeData);
_MTL_PRIVATE_DEF_CLS(MTLPipelineBufferDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLPipelineBufferDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLPointerType);
_MTL_PRIVATE_DEF_CLS(MTLPrimitiveAccelerationStructureDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRasterizationRateLayerArray);
_MTL_PRIVATE_DEF_CLS(MTLRasterizationRateLayerDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRasterizationRateMapDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRasterizationRateSampleArray);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassColorAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassColorAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassDepthAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassSampleBufferAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassSampleBufferAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLRenderPassStencilAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPipelineColorAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPipelineColorAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLRenderPipelineDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPipelineFunctionsDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLRenderPipelineReflection);
_MTL_PRIVATE_DEF_CLS(MTLResourceStatePassDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLSamplerDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLSharedEventHandle);
_MTL_PRIVATE_DEF_CLS(MTLSharedEventListener);
_MTL_PRIVATE_DEF_CLS(MTLSharedTextureHandle);
_MTL_PRIVATE_DEF_CLS(MTLStageInputOutputDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLStencilDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLStitchedLibraryDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLStructMember);
_MTL_PRIVATE_DEF_CLS(MTLStructType);
_MTL_PRIVATE_DEF_CLS(MTLTextureDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLTextureReferenceType);
_MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineColorAttachmentDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineColorAttachmentDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLType);
_MTL_PRIVATE_DEF_CLS(MTLVertexAttribute);
_MTL_PRIVATE_DEF_CLS(MTLVertexAttributeDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLVertexAttributeDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLVertexBufferLayoutDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLVertexBufferLayoutDescriptorArray);
_MTL_PRIVATE_DEF_CLS(MTLVertexDescriptor);
_MTL_PRIVATE_DEF_CLS(MTLVisibleFunctionTableDescriptor);
}
namespace MTL::Private::Protocol
{
_MTL_PRIVATE_DEF_PRO(MTLAccelerationStructure);
_MTL_PRIVATE_DEF_PRO(MTLAccelerationStructureCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLArgumentEncoder);
_MTL_PRIVATE_DEF_PRO(MTLBinaryArchive);
_MTL_PRIVATE_DEF_PRO(MTLBlitCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLBuffer);
_MTL_PRIVATE_DEF_PRO(MTLCommandBuffer);
_MTL_PRIVATE_DEF_PRO(MTLCommandBufferEncoderInfo);
_MTL_PRIVATE_DEF_PRO(MTLCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLCommandQueue);
_MTL_PRIVATE_DEF_PRO(MTLComputeCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLComputePipelineState);
_MTL_PRIVATE_DEF_PRO(MTLCounter);
_MTL_PRIVATE_DEF_PRO(MTLCounterSampleBuffer);
_MTL_PRIVATE_DEF_PRO(MTLCounterSet);
_MTL_PRIVATE_DEF_PRO(MTLDepthStencilState);
_MTL_PRIVATE_DEF_PRO(MTLDevice);
_MTL_PRIVATE_DEF_PRO(MTLDrawable);
_MTL_PRIVATE_DEF_PRO(MTLDynamicLibrary);
_MTL_PRIVATE_DEF_PRO(MTLEvent);
_MTL_PRIVATE_DEF_PRO(MTLFence);
_MTL_PRIVATE_DEF_PRO(MTLFunction);
_MTL_PRIVATE_DEF_PRO(MTLFunctionHandle);
_MTL_PRIVATE_DEF_PRO(MTLFunctionLog);
_MTL_PRIVATE_DEF_PRO(MTLFunctionLogDebugLocation);
_MTL_PRIVATE_DEF_PRO(MTLFunctionStitchingAttribute);
_MTL_PRIVATE_DEF_PRO(MTLFunctionStitchingNode);
_MTL_PRIVATE_DEF_PRO(MTLHeap);
_MTL_PRIVATE_DEF_PRO(MTLIndirectCommandBuffer);
_MTL_PRIVATE_DEF_PRO(MTLIndirectComputeCommand);
_MTL_PRIVATE_DEF_PRO(MTLIndirectRenderCommand);
_MTL_PRIVATE_DEF_PRO(MTLIntersectionFunctionTable);
_MTL_PRIVATE_DEF_PRO(MTLLibrary);
_MTL_PRIVATE_DEF_PRO(MTLLogContainer);
_MTL_PRIVATE_DEF_PRO(MTLParallelRenderCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLRasterizationRateMap);
_MTL_PRIVATE_DEF_PRO(MTLRenderCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLRenderPipelineState);
_MTL_PRIVATE_DEF_PRO(MTLResource);
_MTL_PRIVATE_DEF_PRO(MTLResourceStateCommandEncoder);
_MTL_PRIVATE_DEF_PRO(MTLSamplerState);
_MTL_PRIVATE_DEF_PRO(MTLSharedEvent);
_MTL_PRIVATE_DEF_PRO(MTLTexture);
_MTL_PRIVATE_DEF_PRO(MTLVisibleFunctionTable);
}
namespace MTL::Private::Selector
{
_MTL_PRIVATE_DEF_SEL(GPUEndTime,
"GPUEndTime");
_MTL_PRIVATE_DEF_SEL(GPUStartTime,
"GPUStartTime");
_MTL_PRIVATE_DEF_SEL(URL,
"URL");
_MTL_PRIVATE_DEF_SEL(accelerationStructureCommandEncoder,
"accelerationStructureCommandEncoder");
_MTL_PRIVATE_DEF_SEL(accelerationStructureSizesWithDescriptor_,
"accelerationStructureSizesWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(access,
"access");
_MTL_PRIVATE_DEF_SEL(addCompletedHandler_,
"addCompletedHandler:");
_MTL_PRIVATE_DEF_SEL(addComputePipelineFunctionsWithDescriptor_error_,
"addComputePipelineFunctionsWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(addDebugMarker_range_,
"addDebugMarker:range:");
_MTL_PRIVATE_DEF_SEL(addFunctionWithDescriptor_library_error_,
"addFunctionWithDescriptor:library:error:");
_MTL_PRIVATE_DEF_SEL(addPresentedHandler_,
"addPresentedHandler:");
_MTL_PRIVATE_DEF_SEL(addRenderPipelineFunctionsWithDescriptor_error_,
"addRenderPipelineFunctionsWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(addScheduledHandler_,
"addScheduledHandler:");
_MTL_PRIVATE_DEF_SEL(addTileRenderPipelineFunctionsWithDescriptor_error_,
"addTileRenderPipelineFunctionsWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(alignment,
"alignment");
_MTL_PRIVATE_DEF_SEL(allocatedSize,
"allocatedSize");
_MTL_PRIVATE_DEF_SEL(allowDuplicateIntersectionFunctionInvocation,
"allowDuplicateIntersectionFunctionInvocation");
_MTL_PRIVATE_DEF_SEL(allowGPUOptimizedContents,
"allowGPUOptimizedContents");
_MTL_PRIVATE_DEF_SEL(alphaBlendOperation,
"alphaBlendOperation");
_MTL_PRIVATE_DEF_SEL(areBarycentricCoordsSupported,
"areBarycentricCoordsSupported");
_MTL_PRIVATE_DEF_SEL(areProgrammableSamplePositionsSupported,
"areProgrammableSamplePositionsSupported");
_MTL_PRIVATE_DEF_SEL(areRasterOrderGroupsSupported,
"areRasterOrderGroupsSupported");
_MTL_PRIVATE_DEF_SEL(argumentBuffersSupport,
"argumentBuffersSupport");
_MTL_PRIVATE_DEF_SEL(argumentDescriptor,
"argumentDescriptor");
_MTL_PRIVATE_DEF_SEL(argumentIndex,
"argumentIndex");
_MTL_PRIVATE_DEF_SEL(argumentIndexStride,
"argumentIndexStride");
_MTL_PRIVATE_DEF_SEL(arguments,
"arguments");
_MTL_PRIVATE_DEF_SEL(arrayLength,
"arrayLength");
_MTL_PRIVATE_DEF_SEL(arrayType,
"arrayType");
_MTL_PRIVATE_DEF_SEL(attributeIndex,
"attributeIndex");
_MTL_PRIVATE_DEF_SEL(attributeType,
"attributeType");
_MTL_PRIVATE_DEF_SEL(attributes,
"attributes");
_MTL_PRIVATE_DEF_SEL(backFaceStencil,
"backFaceStencil");
_MTL_PRIVATE_DEF_SEL(binaryArchives,
"binaryArchives");
_MTL_PRIVATE_DEF_SEL(binaryFunctions,
"binaryFunctions");
_MTL_PRIVATE_DEF_SEL(blitCommandEncoder,
"blitCommandEncoder");
_MTL_PRIVATE_DEF_SEL(blitCommandEncoderWithDescriptor_,
"blitCommandEncoderWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(blitPassDescriptor,
"blitPassDescriptor");
_MTL_PRIVATE_DEF_SEL(borderColor,
"borderColor");
_MTL_PRIVATE_DEF_SEL(boundingBoxBuffer,
"boundingBoxBuffer");
_MTL_PRIVATE_DEF_SEL(boundingBoxBufferOffset,
"boundingBoxBufferOffset");
_MTL_PRIVATE_DEF_SEL(boundingBoxBuffers,
"boundingBoxBuffers");
_MTL_PRIVATE_DEF_SEL(boundingBoxCount,
"boundingBoxCount");
_MTL_PRIVATE_DEF_SEL(boundingBoxStride,
"boundingBoxStride");
_MTL_PRIVATE_DEF_SEL(buffer,
"buffer");
_MTL_PRIVATE_DEF_SEL(bufferAlignment,
"bufferAlignment");
_MTL_PRIVATE_DEF_SEL(bufferBytesPerRow,
"bufferBytesPerRow");
_MTL_PRIVATE_DEF_SEL(bufferDataSize,
"bufferDataSize");
_MTL_PRIVATE_DEF_SEL(bufferDataType,
"bufferDataType");
_MTL_PRIVATE_DEF_SEL(bufferIndex,
"bufferIndex");
_MTL_PRIVATE_DEF_SEL(bufferOffset,
"bufferOffset");
_MTL_PRIVATE_DEF_SEL(bufferPointerType,
"bufferPointerType");
_MTL_PRIVATE_DEF_SEL(bufferStructType,
"bufferStructType");
_MTL_PRIVATE_DEF_SEL(buffers,
"buffers");
_MTL_PRIVATE_DEF_SEL(buildAccelerationStructure_descriptor_scratchBuffer_scratchBufferOffset_,
"buildAccelerationStructure:descriptor:scratchBuffer:scratchBufferOffset:");
_MTL_PRIVATE_DEF_SEL(captureObject,
"captureObject");
_MTL_PRIVATE_DEF_SEL(clearBarrier,
"clearBarrier");
_MTL_PRIVATE_DEF_SEL(clearColor,
"clearColor");
_MTL_PRIVATE_DEF_SEL(clearDepth,
"clearDepth");
_MTL_PRIVATE_DEF_SEL(clearStencil,
"clearStencil");
_MTL_PRIVATE_DEF_SEL(colorAttachments,
"colorAttachments");
_MTL_PRIVATE_DEF_SEL(column,
"column");
_MTL_PRIVATE_DEF_SEL(commandBuffer,
"commandBuffer");
_MTL_PRIVATE_DEF_SEL(commandBufferWithDescriptor_,
"commandBufferWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(commandBufferWithUnretainedReferences,
"commandBufferWithUnretainedReferences");
_MTL_PRIVATE_DEF_SEL(commandQueue,
"commandQueue");
_MTL_PRIVATE_DEF_SEL(commandTypes,
"commandTypes");
_MTL_PRIVATE_DEF_SEL(commit,
"commit");
_MTL_PRIVATE_DEF_SEL(compareFunction,
"compareFunction");
_MTL_PRIVATE_DEF_SEL(computeCommandEncoder,
"computeCommandEncoder");
_MTL_PRIVATE_DEF_SEL(computeCommandEncoderWithDescriptor_,
"computeCommandEncoderWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(computeCommandEncoderWithDispatchType_,
"computeCommandEncoderWithDispatchType:");
_MTL_PRIVATE_DEF_SEL(computeFunction,
"computeFunction");
_MTL_PRIVATE_DEF_SEL(computePassDescriptor,
"computePassDescriptor");
_MTL_PRIVATE_DEF_SEL(concurrentDispatchThreadgroups_threadsPerThreadgroup_,
"concurrentDispatchThreadgroups:threadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(concurrentDispatchThreads_threadsPerThreadgroup_,
"concurrentDispatchThreads:threadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(constantBlockAlignment,
"constantBlockAlignment");
_MTL_PRIVATE_DEF_SEL(constantDataAtIndex_,
"constantDataAtIndex:");
_MTL_PRIVATE_DEF_SEL(constantValues,
"constantValues");
_MTL_PRIVATE_DEF_SEL(contents,
"contents");
_MTL_PRIVATE_DEF_SEL(controlDependencies,
"controlDependencies");
_MTL_PRIVATE_DEF_SEL(convertSparsePixelRegions_toTileRegions_withTileSize_alignmentMode_numRegions_,
"convertSparsePixelRegions:toTileRegions:withTileSize:alignmentMode:numRegions:");
_MTL_PRIVATE_DEF_SEL(convertSparseTileRegions_toPixelRegions_withTileSize_numRegions_,
"convertSparseTileRegions:toPixelRegions:withTileSize:numRegions:");
_MTL_PRIVATE_DEF_SEL(copyAccelerationStructure_toAccelerationStructure_,
"copyAccelerationStructure:toAccelerationStructure:");
_MTL_PRIVATE_DEF_SEL(copyAndCompactAccelerationStructure_toAccelerationStructure_,
"copyAndCompactAccelerationStructure:toAccelerationStructure:");
_MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_,
"copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:");
_MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options_,
"copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:options:");
_MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size_,
"copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:");
_MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_,
"copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:");
_MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options_,
"copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:");
_MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_,
"copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:");
_MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_toTexture_destinationSlice_destinationLevel_sliceCount_levelCount_,
"copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel:sliceCount:levelCount:");
_MTL_PRIVATE_DEF_SEL(copyFromTexture_toTexture_,
"copyFromTexture:toTexture:");
_MTL_PRIVATE_DEF_SEL(copyIndirectCommandBuffer_sourceRange_destination_destinationIndex_,
"copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:");
_MTL_PRIVATE_DEF_SEL(copyParameterDataToBuffer_offset_,
"copyParameterDataToBuffer:offset:");
_MTL_PRIVATE_DEF_SEL(counterSet,
"counterSet");
_MTL_PRIVATE_DEF_SEL(counterSets,
"counterSets");
_MTL_PRIVATE_DEF_SEL(counters,
"counters");
_MTL_PRIVATE_DEF_SEL(cpuCacheMode,
"cpuCacheMode");
_MTL_PRIVATE_DEF_SEL(currentAllocatedSize,
"currentAllocatedSize");
_MTL_PRIVATE_DEF_SEL(data,
"data");
_MTL_PRIVATE_DEF_SEL(dataSize,
"dataSize");
_MTL_PRIVATE_DEF_SEL(dataType,
"dataType");
_MTL_PRIVATE_DEF_SEL(dealloc,
"dealloc");
_MTL_PRIVATE_DEF_SEL(debugLocation,
"debugLocation");
_MTL_PRIVATE_DEF_SEL(debugSignposts,
"debugSignposts");
_MTL_PRIVATE_DEF_SEL(defaultCaptureScope,
"defaultCaptureScope");
_MTL_PRIVATE_DEF_SEL(defaultRasterSampleCount,
"defaultRasterSampleCount");
_MTL_PRIVATE_DEF_SEL(depth,
"depth");
_MTL_PRIVATE_DEF_SEL(depthAttachment,
"depthAttachment");
_MTL_PRIVATE_DEF_SEL(depthAttachmentPixelFormat,
"depthAttachmentPixelFormat");
_MTL_PRIVATE_DEF_SEL(depthCompareFunction,
"depthCompareFunction");
_MTL_PRIVATE_DEF_SEL(depthFailureOperation,
"depthFailureOperation");
_MTL_PRIVATE_DEF_SEL(depthPlane,
"depthPlane");
_MTL_PRIVATE_DEF_SEL(depthResolveFilter,
"depthResolveFilter");
_MTL_PRIVATE_DEF_SEL(depthStencilPassOperation,
"depthStencilPassOperation");
_MTL_PRIVATE_DEF_SEL(descriptor,
"descriptor");
_MTL_PRIVATE_DEF_SEL(destination,
"destination");
_MTL_PRIVATE_DEF_SEL(destinationAlphaBlendFactor,
"destinationAlphaBlendFactor");
_MTL_PRIVATE_DEF_SEL(destinationRGBBlendFactor,
"destinationRGBBlendFactor");
_MTL_PRIVATE_DEF_SEL(device,
"device");
_MTL_PRIVATE_DEF_SEL(didModifyRange_,
"didModifyRange:");
_MTL_PRIVATE_DEF_SEL(dispatchQueue,
"dispatchQueue");
_MTL_PRIVATE_DEF_SEL(dispatchThreadgroups_threadsPerThreadgroup_,
"dispatchThreadgroups:threadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup_,
"dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(dispatchThreads_threadsPerThreadgroup_,
"dispatchThreads:threadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(dispatchThreadsPerTile_,
"dispatchThreadsPerTile:");
_MTL_PRIVATE_DEF_SEL(dispatchType,
"dispatchType");
_MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_indirectBuffer_indirectBufferOffset_,
"drawIndexedPatches:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_,
"drawIndexedPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:instanceCount:baseInstance:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_,
"drawIndexedPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:instanceCount:baseInstance:tessellationFactorBuffer:tessellationFactorBufferOffset:tessellationFactorBufferInstanceStride:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_,
"drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_,
"drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_,
"drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:");
_MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset_,
"drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(drawPatches_patchIndexBuffer_patchIndexBufferOffset_indirectBuffer_indirectBufferOffset_,
"drawPatches:patchIndexBuffer:patchIndexBufferOffset:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_,
"drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount:baseInstance:");
_MTL_PRIVATE_DEF_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_,
"drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount:baseInstance:tessellationFactorBuffer:tessellationFactorBufferOffset:tessellationFactorBufferInstanceStride:");
_MTL_PRIVATE_DEF_SEL(drawPrimitives_indirectBuffer_indirectBufferOffset_,
"drawPrimitives:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_,
"drawPrimitives:vertexStart:vertexCount:");
_MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_,
"drawPrimitives:vertexStart:vertexCount:instanceCount:");
_MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_,
"drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:");
_MTL_PRIVATE_DEF_SEL(drawableID,
"drawableID");
_MTL_PRIVATE_DEF_SEL(elementArrayType,
"elementArrayType");
_MTL_PRIVATE_DEF_SEL(elementIsArgumentBuffer,
"elementIsArgumentBuffer");
_MTL_PRIVATE_DEF_SEL(elementPointerType,
"elementPointerType");
_MTL_PRIVATE_DEF_SEL(elementStructType,
"elementStructType");
_MTL_PRIVATE_DEF_SEL(elementTextureReferenceType,
"elementTextureReferenceType");
_MTL_PRIVATE_DEF_SEL(elementType,
"elementType");
_MTL_PRIVATE_DEF_SEL(encodeSignalEvent_value_,
"encodeSignalEvent:value:");
_MTL_PRIVATE_DEF_SEL(encodeWaitForEvent_value_,
"encodeWaitForEvent:value:");
_MTL_PRIVATE_DEF_SEL(encodedLength,
"encodedLength");
_MTL_PRIVATE_DEF_SEL(encoderLabel,
"encoderLabel");
_MTL_PRIVATE_DEF_SEL(endEncoding,
"endEncoding");
_MTL_PRIVATE_DEF_SEL(endOfEncoderSampleIndex,
"endOfEncoderSampleIndex");
_MTL_PRIVATE_DEF_SEL(endOfFragmentSampleIndex,
"endOfFragmentSampleIndex");
_MTL_PRIVATE_DEF_SEL(endOfVertexSampleIndex,
"endOfVertexSampleIndex");
_MTL_PRIVATE_DEF_SEL(enqueue,
"enqueue");
_MTL_PRIVATE_DEF_SEL(error,
"error");
_MTL_PRIVATE_DEF_SEL(errorOptions,
"errorOptions");
_MTL_PRIVATE_DEF_SEL(errorState,
"errorState");
_MTL_PRIVATE_DEF_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_,
"executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(executeCommandsInBuffer_withRange_,
"executeCommandsInBuffer:withRange:");
_MTL_PRIVATE_DEF_SEL(fastMathEnabled,
"fastMathEnabled");
_MTL_PRIVATE_DEF_SEL(fillBuffer_range_value_,
"fillBuffer:range:value:");
_MTL_PRIVATE_DEF_SEL(firstMipmapInTail,
"firstMipmapInTail");
_MTL_PRIVATE_DEF_SEL(format,
"format");
_MTL_PRIVATE_DEF_SEL(fragmentAdditionalBinaryFunctions,
"fragmentAdditionalBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(fragmentArguments,
"fragmentArguments");
_MTL_PRIVATE_DEF_SEL(fragmentBuffers,
"fragmentBuffers");
_MTL_PRIVATE_DEF_SEL(fragmentFunction,
"fragmentFunction");
_MTL_PRIVATE_DEF_SEL(fragmentLinkedFunctions,
"fragmentLinkedFunctions");
_MTL_PRIVATE_DEF_SEL(fragmentPreloadedLibraries,
"fragmentPreloadedLibraries");
_MTL_PRIVATE_DEF_SEL(frontFaceStencil,
"frontFaceStencil");
_MTL_PRIVATE_DEF_SEL(function,
"function");
_MTL_PRIVATE_DEF_SEL(functionConstantsDictionary,
"functionConstantsDictionary");
_MTL_PRIVATE_DEF_SEL(functionCount,
"functionCount");
_MTL_PRIVATE_DEF_SEL(functionDescriptor,
"functionDescriptor");
_MTL_PRIVATE_DEF_SEL(functionGraphs,
"functionGraphs");
_MTL_PRIVATE_DEF_SEL(functionHandleWithFunction_,
"functionHandleWithFunction:");
_MTL_PRIVATE_DEF_SEL(functionHandleWithFunction_stage_,
"functionHandleWithFunction:stage:");
_MTL_PRIVATE_DEF_SEL(functionName,
"functionName");
_MTL_PRIVATE_DEF_SEL(functionNames,
"functionNames");
_MTL_PRIVATE_DEF_SEL(functionType,
"functionType");
_MTL_PRIVATE_DEF_SEL(functions,
"functions");
_MTL_PRIVATE_DEF_SEL(generateMipmapsForTexture_,
"generateMipmapsForTexture:");
_MTL_PRIVATE_DEF_SEL(geometryDescriptors,
"geometryDescriptors");
_MTL_PRIVATE_DEF_SEL(getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_,
"getBytes:bytesPerRow:bytesPerImage:fromRegion:mipmapLevel:slice:");
_MTL_PRIVATE_DEF_SEL(getBytes_bytesPerRow_fromRegion_mipmapLevel_,
"getBytes:bytesPerRow:fromRegion:mipmapLevel:");
_MTL_PRIVATE_DEF_SEL(getDefaultSamplePositions_count_,
"getDefaultSamplePositions:count:");
_MTL_PRIVATE_DEF_SEL(getSamplePositions_count_,
"getSamplePositions:count:");
_MTL_PRIVATE_DEF_SEL(getTextureAccessCounters_region_mipLevel_slice_resetCounters_countersBuffer_countersBufferOffset_,
"getTextureAccessCounters:region:mipLevel:slice:resetCounters:countersBuffer:countersBufferOffset:");
_MTL_PRIVATE_DEF_SEL(groups,
"groups");
_MTL_PRIVATE_DEF_SEL(hasUnifiedMemory,
"hasUnifiedMemory");
_MTL_PRIVATE_DEF_SEL(hazardTrackingMode,
"hazardTrackingMode");
_MTL_PRIVATE_DEF_SEL(heap,
"heap");
_MTL_PRIVATE_DEF_SEL(heapBufferSizeAndAlignWithLength_options_,
"heapBufferSizeAndAlignWithLength:options:");
_MTL_PRIVATE_DEF_SEL(heapOffset,
"heapOffset");
_MTL_PRIVATE_DEF_SEL(heapTextureSizeAndAlignWithDescriptor_,
"heapTextureSizeAndAlignWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(height,
"height");
_MTL_PRIVATE_DEF_SEL(horizontal,
"horizontal");
_MTL_PRIVATE_DEF_SEL(horizontalSampleStorage,
"horizontalSampleStorage");
_MTL_PRIVATE_DEF_SEL(imageblockMemoryLengthForDimensions_,
"imageblockMemoryLengthForDimensions:");
_MTL_PRIVATE_DEF_SEL(imageblockSampleLength,
"imageblockSampleLength");
_MTL_PRIVATE_DEF_SEL(index,
"index");
_MTL_PRIVATE_DEF_SEL(indexBuffer,
"indexBuffer");
_MTL_PRIVATE_DEF_SEL(indexBufferIndex,
"indexBufferIndex");
_MTL_PRIVATE_DEF_SEL(indexBufferOffset,
"indexBufferOffset");
_MTL_PRIVATE_DEF_SEL(indexType,
"indexType");
_MTL_PRIVATE_DEF_SEL(indirectComputeCommandAtIndex_,
"indirectComputeCommandAtIndex:");
_MTL_PRIVATE_DEF_SEL(indirectRenderCommandAtIndex_,
"indirectRenderCommandAtIndex:");
_MTL_PRIVATE_DEF_SEL(inheritBuffers,
"inheritBuffers");
_MTL_PRIVATE_DEF_SEL(inheritPipelineState,
"inheritPipelineState");
_MTL_PRIVATE_DEF_SEL(init,
"init");
_MTL_PRIVATE_DEF_SEL(initWithArgumentIndex_,
"initWithArgumentIndex:");
_MTL_PRIVATE_DEF_SEL(initWithDispatchQueue_,
"initWithDispatchQueue:");
_MTL_PRIVATE_DEF_SEL(initWithFunctionName_nodes_outputNode_attributes_,
"initWithFunctionName:nodes:outputNode:attributes:");
_MTL_PRIVATE_DEF_SEL(initWithName_arguments_controlDependencies_,
"initWithName:arguments:controlDependencies:");
_MTL_PRIVATE_DEF_SEL(initWithSampleCount_,
"initWithSampleCount:");
_MTL_PRIVATE_DEF_SEL(initWithSampleCount_horizontal_vertical_,
"initWithSampleCount:horizontal:vertical:");
_MTL_PRIVATE_DEF_SEL(inputPrimitiveTopology,
"inputPrimitiveTopology");
_MTL_PRIVATE_DEF_SEL(insertDebugCaptureBoundary,
"insertDebugCaptureBoundary");
_MTL_PRIVATE_DEF_SEL(insertDebugSignpost_,
"insertDebugSignpost:");
_MTL_PRIVATE_DEF_SEL(insertLibraries,
"insertLibraries");
_MTL_PRIVATE_DEF_SEL(installName,
"installName");
_MTL_PRIVATE_DEF_SEL(instanceCount,
"instanceCount");
_MTL_PRIVATE_DEF_SEL(instanceDescriptorBuffer,
"instanceDescriptorBuffer");
_MTL_PRIVATE_DEF_SEL(instanceDescriptorBufferOffset,
"instanceDescriptorBufferOffset");
_MTL_PRIVATE_DEF_SEL(instanceDescriptorStride,
"instanceDescriptorStride");
_MTL_PRIVATE_DEF_SEL(instanceDescriptorType,
"instanceDescriptorType");
_MTL_PRIVATE_DEF_SEL(instancedAccelerationStructures,
"instancedAccelerationStructures");
_MTL_PRIVATE_DEF_SEL(intersectionFunctionTableDescriptor,
"intersectionFunctionTableDescriptor");
_MTL_PRIVATE_DEF_SEL(intersectionFunctionTableOffset,
"intersectionFunctionTableOffset");
_MTL_PRIVATE_DEF_SEL(iosurface,
"iosurface");
_MTL_PRIVATE_DEF_SEL(iosurfacePlane,
"iosurfacePlane");
_MTL_PRIVATE_DEF_SEL(isActive,
"isActive");
_MTL_PRIVATE_DEF_SEL(isAliasable,
"isAliasable");
_MTL_PRIVATE_DEF_SEL(isAlphaToCoverageEnabled,
"isAlphaToCoverageEnabled");
_MTL_PRIVATE_DEF_SEL(isAlphaToOneEnabled,
"isAlphaToOneEnabled");
_MTL_PRIVATE_DEF_SEL(isBlendingEnabled,
"isBlendingEnabled");
_MTL_PRIVATE_DEF_SEL(isCapturing,
"isCapturing");
_MTL_PRIVATE_DEF_SEL(isDepth24Stencil8PixelFormatSupported,
"isDepth24Stencil8PixelFormatSupported");
_MTL_PRIVATE_DEF_SEL(isDepthTexture,
"isDepthTexture");
_MTL_PRIVATE_DEF_SEL(isDepthWriteEnabled,
"isDepthWriteEnabled");
_MTL_PRIVATE_DEF_SEL(isFramebufferOnly,
"isFramebufferOnly");
_MTL_PRIVATE_DEF_SEL(isHeadless,
"isHeadless");
_MTL_PRIVATE_DEF_SEL(isLowPower,
"isLowPower");
_MTL_PRIVATE_DEF_SEL(isPatchControlPointData,
"isPatchControlPointData");
_MTL_PRIVATE_DEF_SEL(isPatchData,
"isPatchData");
_MTL_PRIVATE_DEF_SEL(isRasterizationEnabled,
"isRasterizationEnabled");
_MTL_PRIVATE_DEF_SEL(isRemovable,
"isRemovable");
_MTL_PRIVATE_DEF_SEL(isShareable,
"isShareable");
_MTL_PRIVATE_DEF_SEL(isSparse,
"isSparse");
_MTL_PRIVATE_DEF_SEL(isTessellationFactorScaleEnabled,
"isTessellationFactorScaleEnabled");
_MTL_PRIVATE_DEF_SEL(kernelEndTime,
"kernelEndTime");
_MTL_PRIVATE_DEF_SEL(kernelStartTime,
"kernelStartTime");
_MTL_PRIVATE_DEF_SEL(label,
"label");
_MTL_PRIVATE_DEF_SEL(languageVersion,
"languageVersion");
_MTL_PRIVATE_DEF_SEL(layerAtIndex_,
"layerAtIndex:");
_MTL_PRIVATE_DEF_SEL(layerCount,
"layerCount");
_MTL_PRIVATE_DEF_SEL(layers,
"layers");
_MTL_PRIVATE_DEF_SEL(layouts,
"layouts");
_MTL_PRIVATE_DEF_SEL(length,
"length");
_MTL_PRIVATE_DEF_SEL(level,
"level");
_MTL_PRIVATE_DEF_SEL(libraries,
"libraries");
_MTL_PRIVATE_DEF_SEL(libraryType,
"libraryType");
_MTL_PRIVATE_DEF_SEL(line,
"line");
_MTL_PRIVATE_DEF_SEL(linkedFunctions,
"linkedFunctions");
_MTL_PRIVATE_DEF_SEL(loadAction,
"loadAction");
_MTL_PRIVATE_DEF_SEL(location,
"location");
_MTL_PRIVATE_DEF_SEL(locationNumber,
"locationNumber");
_MTL_PRIVATE_DEF_SEL(lodAverage,
"lodAverage");
_MTL_PRIVATE_DEF_SEL(lodMaxClamp,
"lodMaxClamp");
_MTL_PRIVATE_DEF_SEL(lodMinClamp,
"lodMinClamp");
_MTL_PRIVATE_DEF_SEL(logs,
"logs");
_MTL_PRIVATE_DEF_SEL(magFilter,
"magFilter");
_MTL_PRIVATE_DEF_SEL(makeAliasable,
"makeAliasable");
_MTL_PRIVATE_DEF_SEL(mapPhysicalToScreenCoordinates_forLayer_,
"mapPhysicalToScreenCoordinates:forLayer:");
_MTL_PRIVATE_DEF_SEL(mapScreenToPhysicalCoordinates_forLayer_,
"mapScreenToPhysicalCoordinates:forLayer:");
_MTL_PRIVATE_DEF_SEL(maxAnisotropy,
"maxAnisotropy");
_MTL_PRIVATE_DEF_SEL(maxArgumentBufferSamplerCount,
"maxArgumentBufferSamplerCount");
_MTL_PRIVATE_DEF_SEL(maxAvailableSizeWithAlignment_,
"maxAvailableSizeWithAlignment:");
_MTL_PRIVATE_DEF_SEL(maxBufferLength,
"maxBufferLength");
_MTL_PRIVATE_DEF_SEL(maxCallStackDepth,
"maxCallStackDepth");
_MTL_PRIVATE_DEF_SEL(maxFragmentBufferBindCount,
"maxFragmentBufferBindCount");
_MTL_PRIVATE_DEF_SEL(maxFragmentCallStackDepth,
"maxFragmentCallStackDepth");
_MTL_PRIVATE_DEF_SEL(maxKernelBufferBindCount,
"maxKernelBufferBindCount");
_MTL_PRIVATE_DEF_SEL(maxSampleCount,
"maxSampleCount");
_MTL_PRIVATE_DEF_SEL(maxTessellationFactor,
"maxTessellationFactor");
_MTL_PRIVATE_DEF_SEL(maxThreadgroupMemoryLength,
"maxThreadgroupMemoryLength");
_MTL_PRIVATE_DEF_SEL(maxThreadsPerThreadgroup,
"maxThreadsPerThreadgroup");
_MTL_PRIVATE_DEF_SEL(maxTotalThreadsPerThreadgroup,
"maxTotalThreadsPerThreadgroup");
_MTL_PRIVATE_DEF_SEL(maxTransferRate,
"maxTransferRate");
_MTL_PRIVATE_DEF_SEL(maxVertexAmplificationCount,
"maxVertexAmplificationCount");
_MTL_PRIVATE_DEF_SEL(maxVertexBufferBindCount,
"maxVertexBufferBindCount");
_MTL_PRIVATE_DEF_SEL(maxVertexCallStackDepth,
"maxVertexCallStackDepth");
_MTL_PRIVATE_DEF_SEL(memberByName_,
"memberByName:");
_MTL_PRIVATE_DEF_SEL(members,
"members");
_MTL_PRIVATE_DEF_SEL(memoryBarrierWithResources_count_,
"memoryBarrierWithResources:count:");
_MTL_PRIVATE_DEF_SEL(memoryBarrierWithResources_count_afterStages_beforeStages_,
"memoryBarrierWithResources:count:afterStages:beforeStages:");
_MTL_PRIVATE_DEF_SEL(memoryBarrierWithScope_,
"memoryBarrierWithScope:");
_MTL_PRIVATE_DEF_SEL(memoryBarrierWithScope_afterStages_beforeStages_,
"memoryBarrierWithScope:afterStages:beforeStages:");
_MTL_PRIVATE_DEF_SEL(minFilter,
"minFilter");
_MTL_PRIVATE_DEF_SEL(minimumLinearTextureAlignmentForPixelFormat_,
"minimumLinearTextureAlignmentForPixelFormat:");
_MTL_PRIVATE_DEF_SEL(minimumTextureBufferAlignmentForPixelFormat_,
"minimumTextureBufferAlignmentForPixelFormat:");
_MTL_PRIVATE_DEF_SEL(mipFilter,
"mipFilter");
_MTL_PRIVATE_DEF_SEL(mipmapLevelCount,
"mipmapLevelCount");
_MTL_PRIVATE_DEF_SEL(motionEndBorderMode,
"motionEndBorderMode");
_MTL_PRIVATE_DEF_SEL(motionEndTime,
"motionEndTime");
_MTL_PRIVATE_DEF_SEL(motionKeyframeCount,
"motionKeyframeCount");
_MTL_PRIVATE_DEF_SEL(motionStartBorderMode,
"motionStartBorderMode");
_MTL_PRIVATE_DEF_SEL(motionStartTime,
"motionStartTime");
_MTL_PRIVATE_DEF_SEL(motionTransformBuffer,
"motionTransformBuffer");
_MTL_PRIVATE_DEF_SEL(motionTransformBufferOffset,
"motionTransformBufferOffset");
_MTL_PRIVATE_DEF_SEL(motionTransformCount,
"motionTransformCount");
_MTL_PRIVATE_DEF_SEL(mutability,
"mutability");
_MTL_PRIVATE_DEF_SEL(name,
"name");
_MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithDescriptor_,
"newAccelerationStructureWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithSize_,
"newAccelerationStructureWithSize:");
_MTL_PRIVATE_DEF_SEL(newArgumentEncoderForBufferAtIndex_,
"newArgumentEncoderForBufferAtIndex:");
_MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithArguments_,
"newArgumentEncoderWithArguments:");
_MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithBufferIndex_,
"newArgumentEncoderWithBufferIndex:");
_MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithBufferIndex_reflection_,
"newArgumentEncoderWithBufferIndex:reflection:");
_MTL_PRIVATE_DEF_SEL(newBinaryArchiveWithDescriptor_error_,
"newBinaryArchiveWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newBufferWithBytes_length_options_,
"newBufferWithBytes:length:options:");
_MTL_PRIVATE_DEF_SEL(newBufferWithBytesNoCopy_length_options_deallocator_,
"newBufferWithBytesNoCopy:length:options:deallocator:");
_MTL_PRIVATE_DEF_SEL(newBufferWithLength_options_,
"newBufferWithLength:options:");
_MTL_PRIVATE_DEF_SEL(newBufferWithLength_options_offset_,
"newBufferWithLength:options:offset:");
_MTL_PRIVATE_DEF_SEL(newCaptureScopeWithCommandQueue_,
"newCaptureScopeWithCommandQueue:");
_MTL_PRIVATE_DEF_SEL(newCaptureScopeWithDevice_,
"newCaptureScopeWithDevice:");
_MTL_PRIVATE_DEF_SEL(newCommandQueue,
"newCommandQueue");
_MTL_PRIVATE_DEF_SEL(newCommandQueueWithMaxCommandBufferCount_,
"newCommandQueueWithMaxCommandBufferCount:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithAdditionalBinaryFunctions_error_,
"newComputePipelineStateWithAdditionalBinaryFunctions:error:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithDescriptor_options_completionHandler_,
"newComputePipelineStateWithDescriptor:options:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithDescriptor_options_reflection_error_,
"newComputePipelineStateWithDescriptor:options:reflection:error:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_completionHandler_,
"newComputePipelineStateWithFunction:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_error_,
"newComputePipelineStateWithFunction:error:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_options_completionHandler_,
"newComputePipelineStateWithFunction:options:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_options_reflection_error_,
"newComputePipelineStateWithFunction:options:reflection:error:");
_MTL_PRIVATE_DEF_SEL(newCounterSampleBufferWithDescriptor_error_,
"newCounterSampleBufferWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newDefaultLibrary,
"newDefaultLibrary");
_MTL_PRIVATE_DEF_SEL(newDefaultLibraryWithBundle_error_,
"newDefaultLibraryWithBundle:error:");
_MTL_PRIVATE_DEF_SEL(newDepthStencilStateWithDescriptor_,
"newDepthStencilStateWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newDynamicLibrary_error_,
"newDynamicLibrary:error:");
_MTL_PRIVATE_DEF_SEL(newDynamicLibraryWithURL_error_,
"newDynamicLibraryWithURL:error:");
_MTL_PRIVATE_DEF_SEL(newEvent,
"newEvent");
_MTL_PRIVATE_DEF_SEL(newFence,
"newFence");
_MTL_PRIVATE_DEF_SEL(newFunctionWithDescriptor_completionHandler_,
"newFunctionWithDescriptor:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newFunctionWithDescriptor_error_,
"newFunctionWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newFunctionWithName_,
"newFunctionWithName:");
_MTL_PRIVATE_DEF_SEL(newFunctionWithName_constantValues_completionHandler_,
"newFunctionWithName:constantValues:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newFunctionWithName_constantValues_error_,
"newFunctionWithName:constantValues:error:");
_MTL_PRIVATE_DEF_SEL(newHeapWithDescriptor_,
"newHeapWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newIndirectCommandBufferWithDescriptor_maxCommandCount_options_,
"newIndirectCommandBufferWithDescriptor:maxCommandCount:options:");
_MTL_PRIVATE_DEF_SEL(newIntersectionFunctionTableWithDescriptor_,
"newIntersectionFunctionTableWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newIntersectionFunctionTableWithDescriptor_stage_,
"newIntersectionFunctionTableWithDescriptor:stage:");
_MTL_PRIVATE_DEF_SEL(newIntersectionFunctionWithDescriptor_completionHandler_,
"newIntersectionFunctionWithDescriptor:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newIntersectionFunctionWithDescriptor_error_,
"newIntersectionFunctionWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithData_error_,
"newLibraryWithData:error:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithFile_error_,
"newLibraryWithFile:error:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithSource_options_completionHandler_,
"newLibraryWithSource:options:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithSource_options_error_,
"newLibraryWithSource:options:error:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithStitchedDescriptor_completionHandler_,
"newLibraryWithStitchedDescriptor:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithStitchedDescriptor_error_,
"newLibraryWithStitchedDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newLibraryWithURL_error_,
"newLibraryWithURL:error:");
_MTL_PRIVATE_DEF_SEL(newRasterizationRateMapWithDescriptor_,
"newRasterizationRateMapWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newRemoteBufferViewForDevice_,
"newRemoteBufferViewForDevice:");
_MTL_PRIVATE_DEF_SEL(newRemoteTextureViewForDevice_,
"newRemoteTextureViewForDevice:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithAdditionalBinaryFunctions_error_,
"newRenderPipelineStateWithAdditionalBinaryFunctions:error:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_completionHandler_,
"newRenderPipelineStateWithDescriptor:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_error_,
"newRenderPipelineStateWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_options_completionHandler_,
"newRenderPipelineStateWithDescriptor:options:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_options_reflection_error_,
"newRenderPipelineStateWithDescriptor:options:reflection:error:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithTileDescriptor_options_completionHandler_,
"newRenderPipelineStateWithTileDescriptor:options:completionHandler:");
_MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithTileDescriptor_options_reflection_error_,
"newRenderPipelineStateWithTileDescriptor:options:reflection:error:");
_MTL_PRIVATE_DEF_SEL(newSamplerStateWithDescriptor_,
"newSamplerStateWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newSharedEvent,
"newSharedEvent");
_MTL_PRIVATE_DEF_SEL(newSharedEventHandle,
"newSharedEventHandle");
_MTL_PRIVATE_DEF_SEL(newSharedEventWithHandle_,
"newSharedEventWithHandle:");
_MTL_PRIVATE_DEF_SEL(newSharedTextureHandle,
"newSharedTextureHandle");
_MTL_PRIVATE_DEF_SEL(newSharedTextureWithDescriptor_,
"newSharedTextureWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newSharedTextureWithHandle_,
"newSharedTextureWithHandle:");
_MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_,
"newTextureViewWithPixelFormat:");
_MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_,
"newTextureViewWithPixelFormat:textureType:levels:slices:");
_MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_swizzle_,
"newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:");
_MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_,
"newTextureWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_iosurface_plane_,
"newTextureWithDescriptor:iosurface:plane:");
_MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_offset_,
"newTextureWithDescriptor:offset:");
_MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_offset_bytesPerRow_,
"newTextureWithDescriptor:offset:bytesPerRow:");
_MTL_PRIVATE_DEF_SEL(newVisibleFunctionTableWithDescriptor_,
"newVisibleFunctionTableWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(newVisibleFunctionTableWithDescriptor_stage_,
"newVisibleFunctionTableWithDescriptor:stage:");
_MTL_PRIVATE_DEF_SEL(nodes,
"nodes");
_MTL_PRIVATE_DEF_SEL(normalizedCoordinates,
"normalizedCoordinates");
_MTL_PRIVATE_DEF_SEL(notifyListener_atValue_block_,
"notifyListener:atValue:block:");
_MTL_PRIVATE_DEF_SEL(objectAtIndexedSubscript_,
"objectAtIndexedSubscript:");
_MTL_PRIVATE_DEF_SEL(offset,
"offset");
_MTL_PRIVATE_DEF_SEL(opaque,
"opaque");
_MTL_PRIVATE_DEF_SEL(optimizeContentsForCPUAccess_,
"optimizeContentsForCPUAccess:");
_MTL_PRIVATE_DEF_SEL(optimizeContentsForCPUAccess_slice_level_,
"optimizeContentsForCPUAccess:slice:level:");
_MTL_PRIVATE_DEF_SEL(optimizeContentsForGPUAccess_,
"optimizeContentsForGPUAccess:");
_MTL_PRIVATE_DEF_SEL(optimizeContentsForGPUAccess_slice_level_,
"optimizeContentsForGPUAccess:slice:level:");
_MTL_PRIVATE_DEF_SEL(optimizeIndirectCommandBuffer_withRange_,
"optimizeIndirectCommandBuffer:withRange:");
_MTL_PRIVATE_DEF_SEL(options,
"options");
_MTL_PRIVATE_DEF_SEL(outputNode,
"outputNode");
_MTL_PRIVATE_DEF_SEL(outputURL,
"outputURL");
_MTL_PRIVATE_DEF_SEL(parallelRenderCommandEncoderWithDescriptor_,
"parallelRenderCommandEncoderWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(parameterBufferSizeAndAlign,
"parameterBufferSizeAndAlign");
_MTL_PRIVATE_DEF_SEL(parentRelativeLevel,
"parentRelativeLevel");
_MTL_PRIVATE_DEF_SEL(parentRelativeSlice,
"parentRelativeSlice");
_MTL_PRIVATE_DEF_SEL(parentTexture,
"parentTexture");
_MTL_PRIVATE_DEF_SEL(patchControlPointCount,
"patchControlPointCount");
_MTL_PRIVATE_DEF_SEL(patchType,
"patchType");
_MTL_PRIVATE_DEF_SEL(peerCount,
"peerCount");
_MTL_PRIVATE_DEF_SEL(peerGroupID,
"peerGroupID");
_MTL_PRIVATE_DEF_SEL(peerIndex,
"peerIndex");
_MTL_PRIVATE_DEF_SEL(physicalGranularity,
"physicalGranularity");
_MTL_PRIVATE_DEF_SEL(physicalSizeForLayer_,
"physicalSizeForLayer:");
_MTL_PRIVATE_DEF_SEL(pixelFormat,
"pixelFormat");
_MTL_PRIVATE_DEF_SEL(pointerType,
"pointerType");
_MTL_PRIVATE_DEF_SEL(popDebugGroup,
"popDebugGroup");
_MTL_PRIVATE_DEF_SEL(preloadedLibraries,
"preloadedLibraries");
_MTL_PRIVATE_DEF_SEL(preprocessorMacros,
"preprocessorMacros");
_MTL_PRIVATE_DEF_SEL(present,
"present");
_MTL_PRIVATE_DEF_SEL(presentAfterMinimumDuration_,
"presentAfterMinimumDuration:");
_MTL_PRIVATE_DEF_SEL(presentAtTime_,
"presentAtTime:");
_MTL_PRIVATE_DEF_SEL(presentDrawable_,
"presentDrawable:");
_MTL_PRIVATE_DEF_SEL(presentDrawable_afterMinimumDuration_,
"presentDrawable:afterMinimumDuration:");
_MTL_PRIVATE_DEF_SEL(presentDrawable_atTime_,
"presentDrawable:atTime:");
_MTL_PRIVATE_DEF_SEL(presentedTime,
"presentedTime");
_MTL_PRIVATE_DEF_SEL(preserveInvariance,
"preserveInvariance");
_MTL_PRIVATE_DEF_SEL(privateFunctions,
"privateFunctions");
_MTL_PRIVATE_DEF_SEL(pushDebugGroup_,
"pushDebugGroup:");
_MTL_PRIVATE_DEF_SEL(rAddressMode,
"rAddressMode");
_MTL_PRIVATE_DEF_SEL(rasterSampleCount,
"rasterSampleCount");
_MTL_PRIVATE_DEF_SEL(rasterizationRateMap,
"rasterizationRateMap");
_MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_,
"rasterizationRateMapDescriptorWithScreenSize:");
_MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_layer_,
"rasterizationRateMapDescriptorWithScreenSize:layer:");
_MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_layerCount_layers_,
"rasterizationRateMapDescriptorWithScreenSize:layerCount:layers:");
_MTL_PRIVATE_DEF_SEL(readMask,
"readMask");
_MTL_PRIVATE_DEF_SEL(readWriteTextureSupport,
"readWriteTextureSupport");
_MTL_PRIVATE_DEF_SEL(recommendedMaxWorkingSetSize,
"recommendedMaxWorkingSetSize");
_MTL_PRIVATE_DEF_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_,
"refitAccelerationStructure:descriptor:destination:scratchBuffer:scratchBufferOffset:");
_MTL_PRIVATE_DEF_SEL(registryID,
"registryID");
_MTL_PRIVATE_DEF_SEL(remoteStorageBuffer,
"remoteStorageBuffer");
_MTL_PRIVATE_DEF_SEL(remoteStorageTexture,
"remoteStorageTexture");
_MTL_PRIVATE_DEF_SEL(removeAllDebugMarkers,
"removeAllDebugMarkers");
_MTL_PRIVATE_DEF_SEL(renderCommandEncoder,
"renderCommandEncoder");
_MTL_PRIVATE_DEF_SEL(renderCommandEncoderWithDescriptor_,
"renderCommandEncoderWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(renderPassDescriptor,
"renderPassDescriptor");
_MTL_PRIVATE_DEF_SEL(renderTargetArrayLength,
"renderTargetArrayLength");
_MTL_PRIVATE_DEF_SEL(renderTargetHeight,
"renderTargetHeight");
_MTL_PRIVATE_DEF_SEL(renderTargetWidth,
"renderTargetWidth");
_MTL_PRIVATE_DEF_SEL(replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage_,
"replaceRegion:mipmapLevel:slice:withBytes:bytesPerRow:bytesPerImage:");
_MTL_PRIVATE_DEF_SEL(replaceRegion_mipmapLevel_withBytes_bytesPerRow_,
"replaceRegion:mipmapLevel:withBytes:bytesPerRow:");
_MTL_PRIVATE_DEF_SEL(required,
"required");
_MTL_PRIVATE_DEF_SEL(reset,
"reset");
_MTL_PRIVATE_DEF_SEL(resetCommandsInBuffer_withRange_,
"resetCommandsInBuffer:withRange:");
_MTL_PRIVATE_DEF_SEL(resetTextureAccessCounters_region_mipLevel_slice_,
"resetTextureAccessCounters:region:mipLevel:slice:");
_MTL_PRIVATE_DEF_SEL(resetWithRange_,
"resetWithRange:");
_MTL_PRIVATE_DEF_SEL(resolveCounterRange_,
"resolveCounterRange:");
_MTL_PRIVATE_DEF_SEL(resolveCounters_inRange_destinationBuffer_destinationOffset_,
"resolveCounters:inRange:destinationBuffer:destinationOffset:");
_MTL_PRIVATE_DEF_SEL(resolveDepthPlane,
"resolveDepthPlane");
_MTL_PRIVATE_DEF_SEL(resolveLevel,
"resolveLevel");
_MTL_PRIVATE_DEF_SEL(resolveSlice,
"resolveSlice");
_MTL_PRIVATE_DEF_SEL(resolveTexture,
"resolveTexture");
_MTL_PRIVATE_DEF_SEL(resourceOptions,
"resourceOptions");
_MTL_PRIVATE_DEF_SEL(resourceStateCommandEncoder,
"resourceStateCommandEncoder");
_MTL_PRIVATE_DEF_SEL(resourceStateCommandEncoderWithDescriptor_,
"resourceStateCommandEncoderWithDescriptor:");
_MTL_PRIVATE_DEF_SEL(resourceStatePassDescriptor,
"resourceStatePassDescriptor");
_MTL_PRIVATE_DEF_SEL(retainedReferences,
"retainedReferences");
_MTL_PRIVATE_DEF_SEL(rgbBlendOperation,
"rgbBlendOperation");
_MTL_PRIVATE_DEF_SEL(rootResource,
"rootResource");
_MTL_PRIVATE_DEF_SEL(sAddressMode,
"sAddressMode");
_MTL_PRIVATE_DEF_SEL(sampleBuffer,
"sampleBuffer");
_MTL_PRIVATE_DEF_SEL(sampleBufferAttachments,
"sampleBufferAttachments");
_MTL_PRIVATE_DEF_SEL(sampleCount,
"sampleCount");
_MTL_PRIVATE_DEF_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_,
"sampleCountersInBuffer:atSampleIndex:withBarrier:");
_MTL_PRIVATE_DEF_SEL(sampleTimestamps_gpuTimestamp_,
"sampleTimestamps:gpuTimestamp:");
_MTL_PRIVATE_DEF_SEL(screenSize,
"screenSize");
_MTL_PRIVATE_DEF_SEL(serializeToURL_error_,
"serializeToURL:error:");
_MTL_PRIVATE_DEF_SEL(setAccelerationStructure_atBufferIndex_,
"setAccelerationStructure:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setAccelerationStructure_atIndex_,
"setAccelerationStructure:atIndex:");
_MTL_PRIVATE_DEF_SEL(setAccess_,
"setAccess:");
_MTL_PRIVATE_DEF_SEL(setAllowDuplicateIntersectionFunctionInvocation_,
"setAllowDuplicateIntersectionFunctionInvocation:");
_MTL_PRIVATE_DEF_SEL(setAllowGPUOptimizedContents_,
"setAllowGPUOptimizedContents:");
_MTL_PRIVATE_DEF_SEL(setAlphaBlendOperation_,
"setAlphaBlendOperation:");
_MTL_PRIVATE_DEF_SEL(setAlphaToCoverageEnabled_,
"setAlphaToCoverageEnabled:");
_MTL_PRIVATE_DEF_SEL(setAlphaToOneEnabled_,
"setAlphaToOneEnabled:");
_MTL_PRIVATE_DEF_SEL(setArgumentBuffer_offset_,
"setArgumentBuffer:offset:");
_MTL_PRIVATE_DEF_SEL(setArgumentBuffer_startOffset_arrayElement_,
"setArgumentBuffer:startOffset:arrayElement:");
_MTL_PRIVATE_DEF_SEL(setArgumentIndex_,
"setArgumentIndex:");
_MTL_PRIVATE_DEF_SEL(setArguments_,
"setArguments:");
_MTL_PRIVATE_DEF_SEL(setArrayLength_,
"setArrayLength:");
_MTL_PRIVATE_DEF_SEL(setAttributes_,
"setAttributes:");
_MTL_PRIVATE_DEF_SEL(setBackFaceStencil_,
"setBackFaceStencil:");
_MTL_PRIVATE_DEF_SEL(setBarrier,
"setBarrier");
_MTL_PRIVATE_DEF_SEL(setBinaryArchives_,
"setBinaryArchives:");
_MTL_PRIVATE_DEF_SEL(setBinaryFunctions_,
"setBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setBlendColorRed_green_blue_alpha_,
"setBlendColorRed:green:blue:alpha:");
_MTL_PRIVATE_DEF_SEL(setBlendingEnabled_,
"setBlendingEnabled:");
_MTL_PRIVATE_DEF_SEL(setBorderColor_,
"setBorderColor:");
_MTL_PRIVATE_DEF_SEL(setBoundingBoxBuffer_,
"setBoundingBoxBuffer:");
_MTL_PRIVATE_DEF_SEL(setBoundingBoxBufferOffset_,
"setBoundingBoxBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setBoundingBoxBuffers_,
"setBoundingBoxBuffers:");
_MTL_PRIVATE_DEF_SEL(setBoundingBoxCount_,
"setBoundingBoxCount:");
_MTL_PRIVATE_DEF_SEL(setBoundingBoxStride_,
"setBoundingBoxStride:");
_MTL_PRIVATE_DEF_SEL(setBuffer_,
"setBuffer:");
_MTL_PRIVATE_DEF_SEL(setBuffer_offset_atIndex_,
"setBuffer:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setBufferIndex_,
"setBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setBufferOffset_atIndex_,
"setBufferOffset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setBuffers_offsets_withRange_,
"setBuffers:offsets:withRange:");
_MTL_PRIVATE_DEF_SEL(setBytes_length_atIndex_,
"setBytes:length:atIndex:");
_MTL_PRIVATE_DEF_SEL(setCaptureObject_,
"setCaptureObject:");
_MTL_PRIVATE_DEF_SEL(setClearColor_,
"setClearColor:");
_MTL_PRIVATE_DEF_SEL(setClearDepth_,
"setClearDepth:");
_MTL_PRIVATE_DEF_SEL(setClearStencil_,
"setClearStencil:");
_MTL_PRIVATE_DEF_SEL(setColorStoreAction_atIndex_,
"setColorStoreAction:atIndex:");
_MTL_PRIVATE_DEF_SEL(setColorStoreActionOptions_atIndex_,
"setColorStoreActionOptions:atIndex:");
_MTL_PRIVATE_DEF_SEL(setCommandTypes_,
"setCommandTypes:");
_MTL_PRIVATE_DEF_SEL(setCompareFunction_,
"setCompareFunction:");
_MTL_PRIVATE_DEF_SEL(setComputeFunction_,
"setComputeFunction:");
_MTL_PRIVATE_DEF_SEL(setComputePipelineState_,
"setComputePipelineState:");
_MTL_PRIVATE_DEF_SEL(setComputePipelineState_atIndex_,
"setComputePipelineState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setComputePipelineStates_withRange_,
"setComputePipelineStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setConstantBlockAlignment_,
"setConstantBlockAlignment:");
_MTL_PRIVATE_DEF_SEL(setConstantValue_type_atIndex_,
"setConstantValue:type:atIndex:");
_MTL_PRIVATE_DEF_SEL(setConstantValue_type_withName_,
"setConstantValue:type:withName:");
_MTL_PRIVATE_DEF_SEL(setConstantValues_,
"setConstantValues:");
_MTL_PRIVATE_DEF_SEL(setConstantValues_type_withRange_,
"setConstantValues:type:withRange:");
_MTL_PRIVATE_DEF_SEL(setControlDependencies_,
"setControlDependencies:");
_MTL_PRIVATE_DEF_SEL(setCounterSet_,
"setCounterSet:");
_MTL_PRIVATE_DEF_SEL(setCpuCacheMode_,
"setCpuCacheMode:");
_MTL_PRIVATE_DEF_SEL(setCullMode_,
"setCullMode:");
_MTL_PRIVATE_DEF_SEL(setDataType_,
"setDataType:");
_MTL_PRIVATE_DEF_SEL(setDefaultCaptureScope_,
"setDefaultCaptureScope:");
_MTL_PRIVATE_DEF_SEL(setDefaultRasterSampleCount_,
"setDefaultRasterSampleCount:");
_MTL_PRIVATE_DEF_SEL(setDepth_,
"setDepth:");
_MTL_PRIVATE_DEF_SEL(setDepthAttachment_,
"setDepthAttachment:");
_MTL_PRIVATE_DEF_SEL(setDepthAttachmentPixelFormat_,
"setDepthAttachmentPixelFormat:");
_MTL_PRIVATE_DEF_SEL(setDepthBias_slopeScale_clamp_,
"setDepthBias:slopeScale:clamp:");
_MTL_PRIVATE_DEF_SEL(setDepthClipMode_,
"setDepthClipMode:");
_MTL_PRIVATE_DEF_SEL(setDepthCompareFunction_,
"setDepthCompareFunction:");
_MTL_PRIVATE_DEF_SEL(setDepthFailureOperation_,
"setDepthFailureOperation:");
_MTL_PRIVATE_DEF_SEL(setDepthPlane_,
"setDepthPlane:");
_MTL_PRIVATE_DEF_SEL(setDepthResolveFilter_,
"setDepthResolveFilter:");
_MTL_PRIVATE_DEF_SEL(setDepthStencilPassOperation_,
"setDepthStencilPassOperation:");
_MTL_PRIVATE_DEF_SEL(setDepthStencilState_,
"setDepthStencilState:");
_MTL_PRIVATE_DEF_SEL(setDepthStoreAction_,
"setDepthStoreAction:");
_MTL_PRIVATE_DEF_SEL(setDepthStoreActionOptions_,
"setDepthStoreActionOptions:");
_MTL_PRIVATE_DEF_SEL(setDepthWriteEnabled_,
"setDepthWriteEnabled:");
_MTL_PRIVATE_DEF_SEL(setDestination_,
"setDestination:");
_MTL_PRIVATE_DEF_SEL(setDestinationAlphaBlendFactor_,
"setDestinationAlphaBlendFactor:");
_MTL_PRIVATE_DEF_SEL(setDestinationRGBBlendFactor_,
"setDestinationRGBBlendFactor:");
_MTL_PRIVATE_DEF_SEL(setDispatchType_,
"setDispatchType:");
_MTL_PRIVATE_DEF_SEL(setEndOfEncoderSampleIndex_,
"setEndOfEncoderSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setEndOfFragmentSampleIndex_,
"setEndOfFragmentSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setEndOfVertexSampleIndex_,
"setEndOfVertexSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setErrorOptions_,
"setErrorOptions:");
_MTL_PRIVATE_DEF_SEL(setFastMathEnabled_,
"setFastMathEnabled:");
_MTL_PRIVATE_DEF_SEL(setFormat_,
"setFormat:");
_MTL_PRIVATE_DEF_SEL(setFragmentAccelerationStructure_atBufferIndex_,
"setFragmentAccelerationStructure:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentAdditionalBinaryFunctions_,
"setFragmentAdditionalBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setFragmentBuffer_offset_atIndex_,
"setFragmentBuffer:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentBufferOffset_atIndex_,
"setFragmentBufferOffset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentBuffers_offsets_withRange_,
"setFragmentBuffers:offsets:withRange:");
_MTL_PRIVATE_DEF_SEL(setFragmentBytes_length_atIndex_,
"setFragmentBytes:length:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentFunction_,
"setFragmentFunction:");
_MTL_PRIVATE_DEF_SEL(setFragmentIntersectionFunctionTable_atBufferIndex_,
"setFragmentIntersectionFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentIntersectionFunctionTables_withBufferRange_,
"setFragmentIntersectionFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setFragmentLinkedFunctions_,
"setFragmentLinkedFunctions:");
_MTL_PRIVATE_DEF_SEL(setFragmentPreloadedLibraries_,
"setFragmentPreloadedLibraries:");
_MTL_PRIVATE_DEF_SEL(setFragmentSamplerState_atIndex_,
"setFragmentSamplerState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentSamplerState_lodMinClamp_lodMaxClamp_atIndex_,
"setFragmentSamplerState:lodMinClamp:lodMaxClamp:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentSamplerStates_lodMinClamps_lodMaxClamps_withRange_,
"setFragmentSamplerStates:lodMinClamps:lodMaxClamps:withRange:");
_MTL_PRIVATE_DEF_SEL(setFragmentSamplerStates_withRange_,
"setFragmentSamplerStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setFragmentTexture_atIndex_,
"setFragmentTexture:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentTextures_withRange_,
"setFragmentTextures:withRange:");
_MTL_PRIVATE_DEF_SEL(setFragmentVisibleFunctionTable_atBufferIndex_,
"setFragmentVisibleFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setFragmentVisibleFunctionTables_withBufferRange_,
"setFragmentVisibleFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setFrontFaceStencil_,
"setFrontFaceStencil:");
_MTL_PRIVATE_DEF_SEL(setFrontFacingWinding_,
"setFrontFacingWinding:");
_MTL_PRIVATE_DEF_SEL(setFunction_atIndex_,
"setFunction:atIndex:");
_MTL_PRIVATE_DEF_SEL(setFunctionCount_,
"setFunctionCount:");
_MTL_PRIVATE_DEF_SEL(setFunctionGraphs_,
"setFunctionGraphs:");
_MTL_PRIVATE_DEF_SEL(setFunctionName_,
"setFunctionName:");
_MTL_PRIVATE_DEF_SEL(setFunctions_,
"setFunctions:");
_MTL_PRIVATE_DEF_SEL(setFunctions_withRange_,
"setFunctions:withRange:");
_MTL_PRIVATE_DEF_SEL(setGeometryDescriptors_,
"setGeometryDescriptors:");
_MTL_PRIVATE_DEF_SEL(setGroups_,
"setGroups:");
_MTL_PRIVATE_DEF_SEL(setHazardTrackingMode_,
"setHazardTrackingMode:");
_MTL_PRIVATE_DEF_SEL(setHeight_,
"setHeight:");
_MTL_PRIVATE_DEF_SEL(setImageblockSampleLength_,
"setImageblockSampleLength:");
_MTL_PRIVATE_DEF_SEL(setImageblockWidth_height_,
"setImageblockWidth:height:");
_MTL_PRIVATE_DEF_SEL(setIndex_,
"setIndex:");
_MTL_PRIVATE_DEF_SEL(setIndexBuffer_,
"setIndexBuffer:");
_MTL_PRIVATE_DEF_SEL(setIndexBufferIndex_,
"setIndexBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setIndexBufferOffset_,
"setIndexBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setIndexType_,
"setIndexType:");
_MTL_PRIVATE_DEF_SEL(setIndirectCommandBuffer_atIndex_,
"setIndirectCommandBuffer:atIndex:");
_MTL_PRIVATE_DEF_SEL(setIndirectCommandBuffers_withRange_,
"setIndirectCommandBuffers:withRange:");
_MTL_PRIVATE_DEF_SEL(setInheritBuffers_,
"setInheritBuffers:");
_MTL_PRIVATE_DEF_SEL(setInheritPipelineState_,
"setInheritPipelineState:");
_MTL_PRIVATE_DEF_SEL(setInputPrimitiveTopology_,
"setInputPrimitiveTopology:");
_MTL_PRIVATE_DEF_SEL(setInsertLibraries_,
"setInsertLibraries:");
_MTL_PRIVATE_DEF_SEL(setInstallName_,
"setInstallName:");
_MTL_PRIVATE_DEF_SEL(setInstanceCount_,
"setInstanceCount:");
_MTL_PRIVATE_DEF_SEL(setInstanceDescriptorBuffer_,
"setInstanceDescriptorBuffer:");
_MTL_PRIVATE_DEF_SEL(setInstanceDescriptorBufferOffset_,
"setInstanceDescriptorBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setInstanceDescriptorStride_,
"setInstanceDescriptorStride:");
_MTL_PRIVATE_DEF_SEL(setInstanceDescriptorType_,
"setInstanceDescriptorType:");
_MTL_PRIVATE_DEF_SEL(setInstancedAccelerationStructures_,
"setInstancedAccelerationStructures:");
_MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTable_atBufferIndex_,
"setIntersectionFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTable_atIndex_,
"setIntersectionFunctionTable:atIndex:");
_MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTableOffset_,
"setIntersectionFunctionTableOffset:");
_MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTables_withBufferRange_,
"setIntersectionFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTables_withRange_,
"setIntersectionFunctionTables:withRange:");
_MTL_PRIVATE_DEF_SEL(setKernelBuffer_offset_atIndex_,
"setKernelBuffer:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setLabel_,
"setLabel:");
_MTL_PRIVATE_DEF_SEL(setLanguageVersion_,
"setLanguageVersion:");
_MTL_PRIVATE_DEF_SEL(setLayer_atIndex_,
"setLayer:atIndex:");
_MTL_PRIVATE_DEF_SEL(setLevel_,
"setLevel:");
_MTL_PRIVATE_DEF_SEL(setLibraries_,
"setLibraries:");
_MTL_PRIVATE_DEF_SEL(setLibraryType_,
"setLibraryType:");
_MTL_PRIVATE_DEF_SEL(setLinkedFunctions_,
"setLinkedFunctions:");
_MTL_PRIVATE_DEF_SEL(setLoadAction_,
"setLoadAction:");
_MTL_PRIVATE_DEF_SEL(setLodAverage_,
"setLodAverage:");
_MTL_PRIVATE_DEF_SEL(setLodMaxClamp_,
"setLodMaxClamp:");
_MTL_PRIVATE_DEF_SEL(setLodMinClamp_,
"setLodMinClamp:");
_MTL_PRIVATE_DEF_SEL(setMagFilter_,
"setMagFilter:");
_MTL_PRIVATE_DEF_SEL(setMaxAnisotropy_,
"setMaxAnisotropy:");
_MTL_PRIVATE_DEF_SEL(setMaxCallStackDepth_,
"setMaxCallStackDepth:");
_MTL_PRIVATE_DEF_SEL(setMaxFragmentBufferBindCount_,
"setMaxFragmentBufferBindCount:");
_MTL_PRIVATE_DEF_SEL(setMaxFragmentCallStackDepth_,
"setMaxFragmentCallStackDepth:");
_MTL_PRIVATE_DEF_SEL(setMaxKernelBufferBindCount_,
"setMaxKernelBufferBindCount:");
_MTL_PRIVATE_DEF_SEL(setMaxTessellationFactor_,
"setMaxTessellationFactor:");
_MTL_PRIVATE_DEF_SEL(setMaxTotalThreadsPerThreadgroup_,
"setMaxTotalThreadsPerThreadgroup:");
_MTL_PRIVATE_DEF_SEL(setMaxVertexAmplificationCount_,
"setMaxVertexAmplificationCount:");
_MTL_PRIVATE_DEF_SEL(setMaxVertexBufferBindCount_,
"setMaxVertexBufferBindCount:");
_MTL_PRIVATE_DEF_SEL(setMaxVertexCallStackDepth_,
"setMaxVertexCallStackDepth:");
_MTL_PRIVATE_DEF_SEL(setMinFilter_,
"setMinFilter:");
_MTL_PRIVATE_DEF_SEL(setMipFilter_,
"setMipFilter:");
_MTL_PRIVATE_DEF_SEL(setMipmapLevelCount_,
"setMipmapLevelCount:");
_MTL_PRIVATE_DEF_SEL(setMotionEndBorderMode_,
"setMotionEndBorderMode:");
_MTL_PRIVATE_DEF_SEL(setMotionEndTime_,
"setMotionEndTime:");
_MTL_PRIVATE_DEF_SEL(setMotionKeyframeCount_,
"setMotionKeyframeCount:");
_MTL_PRIVATE_DEF_SEL(setMotionStartBorderMode_,
"setMotionStartBorderMode:");
_MTL_PRIVATE_DEF_SEL(setMotionStartTime_,
"setMotionStartTime:");
_MTL_PRIVATE_DEF_SEL(setMotionTransformBuffer_,
"setMotionTransformBuffer:");
_MTL_PRIVATE_DEF_SEL(setMotionTransformBufferOffset_,
"setMotionTransformBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setMotionTransformCount_,
"setMotionTransformCount:");
_MTL_PRIVATE_DEF_SEL(setMutability_,
"setMutability:");
_MTL_PRIVATE_DEF_SEL(setName_,
"setName:");
_MTL_PRIVATE_DEF_SEL(setNodes_,
"setNodes:");
_MTL_PRIVATE_DEF_SEL(setNormalizedCoordinates_,
"setNormalizedCoordinates:");
_MTL_PRIVATE_DEF_SEL(setObject_atIndexedSubscript_,
"setObject:atIndexedSubscript:");
_MTL_PRIVATE_DEF_SEL(setOffset_,
"setOffset:");
_MTL_PRIVATE_DEF_SEL(setOpaque_,
"setOpaque:");
_MTL_PRIVATE_DEF_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_atIndex_,
"setOpaqueTriangleIntersectionFunctionWithSignature:atIndex:");
_MTL_PRIVATE_DEF_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_withRange_,
"setOpaqueTriangleIntersectionFunctionWithSignature:withRange:");
_MTL_PRIVATE_DEF_SEL(setOptions_,
"setOptions:");
_MTL_PRIVATE_DEF_SEL(setOutputNode_,
"setOutputNode:");
_MTL_PRIVATE_DEF_SEL(setOutputURL_,
"setOutputURL:");
_MTL_PRIVATE_DEF_SEL(setPixelFormat_,
"setPixelFormat:");
_MTL_PRIVATE_DEF_SEL(setPreloadedLibraries_,
"setPreloadedLibraries:");
_MTL_PRIVATE_DEF_SEL(setPreprocessorMacros_,
"setPreprocessorMacros:");
_MTL_PRIVATE_DEF_SEL(setPreserveInvariance_,
"setPreserveInvariance:");
_MTL_PRIVATE_DEF_SEL(setPrivateFunctions_,
"setPrivateFunctions:");
_MTL_PRIVATE_DEF_SEL(setPurgeableState_,
"setPurgeableState:");
_MTL_PRIVATE_DEF_SEL(setRAddressMode_,
"setRAddressMode:");
_MTL_PRIVATE_DEF_SEL(setRasterSampleCount_,
"setRasterSampleCount:");
_MTL_PRIVATE_DEF_SEL(setRasterizationEnabled_,
"setRasterizationEnabled:");
_MTL_PRIVATE_DEF_SEL(setRasterizationRateMap_,
"setRasterizationRateMap:");
_MTL_PRIVATE_DEF_SEL(setReadMask_,
"setReadMask:");
_MTL_PRIVATE_DEF_SEL(setRenderPipelineState_,
"setRenderPipelineState:");
_MTL_PRIVATE_DEF_SEL(setRenderPipelineState_atIndex_,
"setRenderPipelineState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setRenderPipelineStates_withRange_,
"setRenderPipelineStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setRenderTargetArrayLength_,
"setRenderTargetArrayLength:");
_MTL_PRIVATE_DEF_SEL(setRenderTargetHeight_,
"setRenderTargetHeight:");
_MTL_PRIVATE_DEF_SEL(setRenderTargetWidth_,
"setRenderTargetWidth:");
_MTL_PRIVATE_DEF_SEL(setResolveDepthPlane_,
"setResolveDepthPlane:");
_MTL_PRIVATE_DEF_SEL(setResolveLevel_,
"setResolveLevel:");
_MTL_PRIVATE_DEF_SEL(setResolveSlice_,
"setResolveSlice:");
_MTL_PRIVATE_DEF_SEL(setResolveTexture_,
"setResolveTexture:");
_MTL_PRIVATE_DEF_SEL(setResourceOptions_,
"setResourceOptions:");
_MTL_PRIVATE_DEF_SEL(setRetainedReferences_,
"setRetainedReferences:");
_MTL_PRIVATE_DEF_SEL(setRgbBlendOperation_,
"setRgbBlendOperation:");
_MTL_PRIVATE_DEF_SEL(setSAddressMode_,
"setSAddressMode:");
_MTL_PRIVATE_DEF_SEL(setSampleBuffer_,
"setSampleBuffer:");
_MTL_PRIVATE_DEF_SEL(setSampleCount_,
"setSampleCount:");
_MTL_PRIVATE_DEF_SEL(setSamplePositions_count_,
"setSamplePositions:count:");
_MTL_PRIVATE_DEF_SEL(setSamplerState_atIndex_,
"setSamplerState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setSamplerState_lodMinClamp_lodMaxClamp_atIndex_,
"setSamplerState:lodMinClamp:lodMaxClamp:atIndex:");
_MTL_PRIVATE_DEF_SEL(setSamplerStates_lodMinClamps_lodMaxClamps_withRange_,
"setSamplerStates:lodMinClamps:lodMaxClamps:withRange:");
_MTL_PRIVATE_DEF_SEL(setSamplerStates_withRange_,
"setSamplerStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setScissorRect_,
"setScissorRect:");
_MTL_PRIVATE_DEF_SEL(setScissorRects_count_,
"setScissorRects:count:");
_MTL_PRIVATE_DEF_SEL(setScreenSize_,
"setScreenSize:");
_MTL_PRIVATE_DEF_SEL(setSignaledValue_,
"setSignaledValue:");
_MTL_PRIVATE_DEF_SEL(setSize_,
"setSize:");
_MTL_PRIVATE_DEF_SEL(setSlice_,
"setSlice:");
_MTL_PRIVATE_DEF_SEL(setSourceAlphaBlendFactor_,
"setSourceAlphaBlendFactor:");
_MTL_PRIVATE_DEF_SEL(setSourceRGBBlendFactor_,
"setSourceRGBBlendFactor:");
_MTL_PRIVATE_DEF_SEL(setSpecializedName_,
"setSpecializedName:");
_MTL_PRIVATE_DEF_SEL(setStageInRegion_,
"setStageInRegion:");
_MTL_PRIVATE_DEF_SEL(setStageInRegionWithIndirectBuffer_indirectBufferOffset_,
"setStageInRegionWithIndirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setStageInputDescriptor_,
"setStageInputDescriptor:");
_MTL_PRIVATE_DEF_SEL(setStartOfEncoderSampleIndex_,
"setStartOfEncoderSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setStartOfFragmentSampleIndex_,
"setStartOfFragmentSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setStartOfVertexSampleIndex_,
"setStartOfVertexSampleIndex:");
_MTL_PRIVATE_DEF_SEL(setStencilAttachment_,
"setStencilAttachment:");
_MTL_PRIVATE_DEF_SEL(setStencilAttachmentPixelFormat_,
"setStencilAttachmentPixelFormat:");
_MTL_PRIVATE_DEF_SEL(setStencilCompareFunction_,
"setStencilCompareFunction:");
_MTL_PRIVATE_DEF_SEL(setStencilFailureOperation_,
"setStencilFailureOperation:");
_MTL_PRIVATE_DEF_SEL(setStencilFrontReferenceValue_backReferenceValue_,
"setStencilFrontReferenceValue:backReferenceValue:");
_MTL_PRIVATE_DEF_SEL(setStencilReferenceValue_,
"setStencilReferenceValue:");
_MTL_PRIVATE_DEF_SEL(setStencilResolveFilter_,
"setStencilResolveFilter:");
_MTL_PRIVATE_DEF_SEL(setStencilStoreAction_,
"setStencilStoreAction:");
_MTL_PRIVATE_DEF_SEL(setStencilStoreActionOptions_,
"setStencilStoreActionOptions:");
_MTL_PRIVATE_DEF_SEL(setStepFunction_,
"setStepFunction:");
_MTL_PRIVATE_DEF_SEL(setStepRate_,
"setStepRate:");
_MTL_PRIVATE_DEF_SEL(setStorageMode_,
"setStorageMode:");
_MTL_PRIVATE_DEF_SEL(setStoreAction_,
"setStoreAction:");
_MTL_PRIVATE_DEF_SEL(setStoreActionOptions_,
"setStoreActionOptions:");
_MTL_PRIVATE_DEF_SEL(setStride_,
"setStride:");
_MTL_PRIVATE_DEF_SEL(setSupportAddingBinaryFunctions_,
"setSupportAddingBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setSupportAddingFragmentBinaryFunctions_,
"setSupportAddingFragmentBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setSupportAddingVertexBinaryFunctions_,
"setSupportAddingVertexBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setSupportArgumentBuffers_,
"setSupportArgumentBuffers:");
_MTL_PRIVATE_DEF_SEL(setSupportIndirectCommandBuffers_,
"setSupportIndirectCommandBuffers:");
_MTL_PRIVATE_DEF_SEL(setSwizzle_,
"setSwizzle:");
_MTL_PRIVATE_DEF_SEL(setTAddressMode_,
"setTAddressMode:");
_MTL_PRIVATE_DEF_SEL(setTessellationControlPointIndexType_,
"setTessellationControlPointIndexType:");
_MTL_PRIVATE_DEF_SEL(setTessellationFactorBuffer_offset_instanceStride_,
"setTessellationFactorBuffer:offset:instanceStride:");
_MTL_PRIVATE_DEF_SEL(setTessellationFactorFormat_,
"setTessellationFactorFormat:");
_MTL_PRIVATE_DEF_SEL(setTessellationFactorScale_,
"setTessellationFactorScale:");
_MTL_PRIVATE_DEF_SEL(setTessellationFactorScaleEnabled_,
"setTessellationFactorScaleEnabled:");
_MTL_PRIVATE_DEF_SEL(setTessellationFactorStepFunction_,
"setTessellationFactorStepFunction:");
_MTL_PRIVATE_DEF_SEL(setTessellationOutputWindingOrder_,
"setTessellationOutputWindingOrder:");
_MTL_PRIVATE_DEF_SEL(setTessellationPartitionMode_,
"setTessellationPartitionMode:");
_MTL_PRIVATE_DEF_SEL(setTexture_,
"setTexture:");
_MTL_PRIVATE_DEF_SEL(setTexture_atIndex_,
"setTexture:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTextureType_,
"setTextureType:");
_MTL_PRIVATE_DEF_SEL(setTextures_withRange_,
"setTextures:withRange:");
_MTL_PRIVATE_DEF_SEL(setThreadGroupSizeIsMultipleOfThreadExecutionWidth_,
"setThreadGroupSizeIsMultipleOfThreadExecutionWidth:");
_MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_,
"setThreadgroupMemoryLength:");
_MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_atIndex_,
"setThreadgroupMemoryLength:atIndex:");
_MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_offset_atIndex_,
"setThreadgroupMemoryLength:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setThreadgroupSizeMatchesTileSize_,
"setThreadgroupSizeMatchesTileSize:");
_MTL_PRIVATE_DEF_SEL(setTileAccelerationStructure_atBufferIndex_,
"setTileAccelerationStructure:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setTileAdditionalBinaryFunctions_,
"setTileAdditionalBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setTileBuffer_offset_atIndex_,
"setTileBuffer:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileBufferOffset_atIndex_,
"setTileBufferOffset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileBuffers_offsets_withRange_,
"setTileBuffers:offsets:withRange:");
_MTL_PRIVATE_DEF_SEL(setTileBytes_length_atIndex_,
"setTileBytes:length:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileFunction_,
"setTileFunction:");
_MTL_PRIVATE_DEF_SEL(setTileHeight_,
"setTileHeight:");
_MTL_PRIVATE_DEF_SEL(setTileIntersectionFunctionTable_atBufferIndex_,
"setTileIntersectionFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setTileIntersectionFunctionTables_withBufferRange_,
"setTileIntersectionFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setTileSamplerState_atIndex_,
"setTileSamplerState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileSamplerState_lodMinClamp_lodMaxClamp_atIndex_,
"setTileSamplerState:lodMinClamp:lodMaxClamp:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileSamplerStates_lodMinClamps_lodMaxClamps_withRange_,
"setTileSamplerStates:lodMinClamps:lodMaxClamps:withRange:");
_MTL_PRIVATE_DEF_SEL(setTileSamplerStates_withRange_,
"setTileSamplerStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setTileTexture_atIndex_,
"setTileTexture:atIndex:");
_MTL_PRIVATE_DEF_SEL(setTileTextures_withRange_,
"setTileTextures:withRange:");
_MTL_PRIVATE_DEF_SEL(setTileVisibleFunctionTable_atBufferIndex_,
"setTileVisibleFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setTileVisibleFunctionTables_withBufferRange_,
"setTileVisibleFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setTileWidth_,
"setTileWidth:");
_MTL_PRIVATE_DEF_SEL(setTriangleCount_,
"setTriangleCount:");
_MTL_PRIVATE_DEF_SEL(setTriangleFillMode_,
"setTriangleFillMode:");
_MTL_PRIVATE_DEF_SEL(setType_,
"setType:");
_MTL_PRIVATE_DEF_SEL(setUrl_,
"setUrl:");
_MTL_PRIVATE_DEF_SEL(setUsage_,
"setUsage:");
_MTL_PRIVATE_DEF_SEL(setVertexAccelerationStructure_atBufferIndex_,
"setVertexAccelerationStructure:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexAdditionalBinaryFunctions_,
"setVertexAdditionalBinaryFunctions:");
_MTL_PRIVATE_DEF_SEL(setVertexAmplificationCount_viewMappings_,
"setVertexAmplificationCount:viewMappings:");
_MTL_PRIVATE_DEF_SEL(setVertexBuffer_,
"setVertexBuffer:");
_MTL_PRIVATE_DEF_SEL(setVertexBuffer_offset_atIndex_,
"setVertexBuffer:offset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexBufferOffset_,
"setVertexBufferOffset:");
_MTL_PRIVATE_DEF_SEL(setVertexBufferOffset_atIndex_,
"setVertexBufferOffset:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexBuffers_,
"setVertexBuffers:");
_MTL_PRIVATE_DEF_SEL(setVertexBuffers_offsets_withRange_,
"setVertexBuffers:offsets:withRange:");
_MTL_PRIVATE_DEF_SEL(setVertexBytes_length_atIndex_,
"setVertexBytes:length:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexDescriptor_,
"setVertexDescriptor:");
_MTL_PRIVATE_DEF_SEL(setVertexFunction_,
"setVertexFunction:");
_MTL_PRIVATE_DEF_SEL(setVertexIntersectionFunctionTable_atBufferIndex_,
"setVertexIntersectionFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexIntersectionFunctionTables_withBufferRange_,
"setVertexIntersectionFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setVertexLinkedFunctions_,
"setVertexLinkedFunctions:");
_MTL_PRIVATE_DEF_SEL(setVertexPreloadedLibraries_,
"setVertexPreloadedLibraries:");
_MTL_PRIVATE_DEF_SEL(setVertexSamplerState_atIndex_,
"setVertexSamplerState:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexSamplerState_lodMinClamp_lodMaxClamp_atIndex_,
"setVertexSamplerState:lodMinClamp:lodMaxClamp:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexSamplerStates_lodMinClamps_lodMaxClamps_withRange_,
"setVertexSamplerStates:lodMinClamps:lodMaxClamps:withRange:");
_MTL_PRIVATE_DEF_SEL(setVertexSamplerStates_withRange_,
"setVertexSamplerStates:withRange:");
_MTL_PRIVATE_DEF_SEL(setVertexStride_,
"setVertexStride:");
_MTL_PRIVATE_DEF_SEL(setVertexTexture_atIndex_,
"setVertexTexture:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexTextures_withRange_,
"setVertexTextures:withRange:");
_MTL_PRIVATE_DEF_SEL(setVertexVisibleFunctionTable_atBufferIndex_,
"setVertexVisibleFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setVertexVisibleFunctionTables_withBufferRange_,
"setVertexVisibleFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setViewport_,
"setViewport:");
_MTL_PRIVATE_DEF_SEL(setViewports_count_,
"setViewports:count:");
_MTL_PRIVATE_DEF_SEL(setVisibilityResultBuffer_,
"setVisibilityResultBuffer:");
_MTL_PRIVATE_DEF_SEL(setVisibilityResultMode_offset_,
"setVisibilityResultMode:offset:");
_MTL_PRIVATE_DEF_SEL(setVisibleFunctionTable_atBufferIndex_,
"setVisibleFunctionTable:atBufferIndex:");
_MTL_PRIVATE_DEF_SEL(setVisibleFunctionTable_atIndex_,
"setVisibleFunctionTable:atIndex:");
_MTL_PRIVATE_DEF_SEL(setVisibleFunctionTables_withBufferRange_,
"setVisibleFunctionTables:withBufferRange:");
_MTL_PRIVATE_DEF_SEL(setVisibleFunctionTables_withRange_,
"setVisibleFunctionTables:withRange:");
_MTL_PRIVATE_DEF_SEL(setWidth_,
"setWidth:");
_MTL_PRIVATE_DEF_SEL(setWriteMask_,
"setWriteMask:");
_MTL_PRIVATE_DEF_SEL(sharedCaptureManager,
"sharedCaptureManager");
_MTL_PRIVATE_DEF_SEL(signaledValue,
"signaledValue");
_MTL_PRIVATE_DEF_SEL(size,
"size");
_MTL_PRIVATE_DEF_SEL(slice,
"slice");
_MTL_PRIVATE_DEF_SEL(sourceAlphaBlendFactor,
"sourceAlphaBlendFactor");
_MTL_PRIVATE_DEF_SEL(sourceRGBBlendFactor,
"sourceRGBBlendFactor");
_MTL_PRIVATE_DEF_SEL(sparseTileSizeInBytes,
"sparseTileSizeInBytes");
_MTL_PRIVATE_DEF_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_,
"sparseTileSizeWithTextureType:pixelFormat:sampleCount:");
_MTL_PRIVATE_DEF_SEL(specializedName,
"specializedName");
_MTL_PRIVATE_DEF_SEL(stageInputAttributes,
"stageInputAttributes");
_MTL_PRIVATE_DEF_SEL(stageInputDescriptor,
"stageInputDescriptor");
_MTL_PRIVATE_DEF_SEL(stageInputOutputDescriptor,
"stageInputOutputDescriptor");
_MTL_PRIVATE_DEF_SEL(startCaptureWithCommandQueue_,
"startCaptureWithCommandQueue:");
_MTL_PRIVATE_DEF_SEL(startCaptureWithDescriptor_error_,
"startCaptureWithDescriptor:error:");
_MTL_PRIVATE_DEF_SEL(startCaptureWithDevice_,
"startCaptureWithDevice:");
_MTL_PRIVATE_DEF_SEL(startCaptureWithScope_,
"startCaptureWithScope:");
_MTL_PRIVATE_DEF_SEL(startOfEncoderSampleIndex,
"startOfEncoderSampleIndex");
_MTL_PRIVATE_DEF_SEL(startOfFragmentSampleIndex,
"startOfFragmentSampleIndex");
_MTL_PRIVATE_DEF_SEL(startOfVertexSampleIndex,
"startOfVertexSampleIndex");
_MTL_PRIVATE_DEF_SEL(staticThreadgroupMemoryLength,
"staticThreadgroupMemoryLength");
_MTL_PRIVATE_DEF_SEL(status,
"status");
_MTL_PRIVATE_DEF_SEL(stencilAttachment,
"stencilAttachment");
_MTL_PRIVATE_DEF_SEL(stencilAttachmentPixelFormat,
"stencilAttachmentPixelFormat");
_MTL_PRIVATE_DEF_SEL(stencilCompareFunction,
"stencilCompareFunction");
_MTL_PRIVATE_DEF_SEL(stencilFailureOperation,
"stencilFailureOperation");
_MTL_PRIVATE_DEF_SEL(stencilResolveFilter,
"stencilResolveFilter");
_MTL_PRIVATE_DEF_SEL(stepFunction,
"stepFunction");
_MTL_PRIVATE_DEF_SEL(stepRate,
"stepRate");
_MTL_PRIVATE_DEF_SEL(stopCapture,
"stopCapture");
_MTL_PRIVATE_DEF_SEL(storageMode,
"storageMode");
_MTL_PRIVATE_DEF_SEL(storeAction,
"storeAction");
_MTL_PRIVATE_DEF_SEL(storeActionOptions,
"storeActionOptions");
_MTL_PRIVATE_DEF_SEL(stride,
"stride");
_MTL_PRIVATE_DEF_SEL(structType,
"structType");
_MTL_PRIVATE_DEF_SEL(supportAddingBinaryFunctions,
"supportAddingBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(supportAddingFragmentBinaryFunctions,
"supportAddingFragmentBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(supportAddingVertexBinaryFunctions,
"supportAddingVertexBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(supportArgumentBuffers,
"supportArgumentBuffers");
_MTL_PRIVATE_DEF_SEL(supportIndirectCommandBuffers,
"supportIndirectCommandBuffers");
_MTL_PRIVATE_DEF_SEL(supports32BitFloatFiltering,
"supports32BitFloatFiltering");
_MTL_PRIVATE_DEF_SEL(supports32BitMSAA,
"supports32BitMSAA");
_MTL_PRIVATE_DEF_SEL(supportsBCTextureCompression,
"supportsBCTextureCompression");
_MTL_PRIVATE_DEF_SEL(supportsCounterSampling_,
"supportsCounterSampling:");
_MTL_PRIVATE_DEF_SEL(supportsDestination_,
"supportsDestination:");
_MTL_PRIVATE_DEF_SEL(supportsDynamicLibraries,
"supportsDynamicLibraries");
_MTL_PRIVATE_DEF_SEL(supportsFamily_,
"supportsFamily:");
_MTL_PRIVATE_DEF_SEL(supportsFeatureSet_,
"supportsFeatureSet:");
_MTL_PRIVATE_DEF_SEL(supportsFunctionPointers,
"supportsFunctionPointers");
_MTL_PRIVATE_DEF_SEL(supportsFunctionPointersFromRender,
"supportsFunctionPointersFromRender");
_MTL_PRIVATE_DEF_SEL(supportsPrimitiveMotionBlur,
"supportsPrimitiveMotionBlur");
_MTL_PRIVATE_DEF_SEL(supportsPullModelInterpolation,
"supportsPullModelInterpolation");
_MTL_PRIVATE_DEF_SEL(supportsQueryTextureLOD,
"supportsQueryTextureLOD");
_MTL_PRIVATE_DEF_SEL(supportsRasterizationRateMapWithLayerCount_,
"supportsRasterizationRateMapWithLayerCount:");
_MTL_PRIVATE_DEF_SEL(supportsRaytracing,
"supportsRaytracing");
_MTL_PRIVATE_DEF_SEL(supportsRaytracingFromRender,
"supportsRaytracingFromRender");
_MTL_PRIVATE_DEF_SEL(supportsRenderDynamicLibraries,
"supportsRenderDynamicLibraries");
_MTL_PRIVATE_DEF_SEL(supportsShaderBarycentricCoordinates,
"supportsShaderBarycentricCoordinates");
_MTL_PRIVATE_DEF_SEL(supportsTextureSampleCount_,
"supportsTextureSampleCount:");
_MTL_PRIVATE_DEF_SEL(supportsVertexAmplificationCount_,
"supportsVertexAmplificationCount:");
_MTL_PRIVATE_DEF_SEL(swizzle,
"swizzle");
_MTL_PRIVATE_DEF_SEL(synchronizeResource_,
"synchronizeResource:");
_MTL_PRIVATE_DEF_SEL(synchronizeTexture_slice_level_,
"synchronizeTexture:slice:level:");
_MTL_PRIVATE_DEF_SEL(tAddressMode,
"tAddressMode");
_MTL_PRIVATE_DEF_SEL(tailSizeInBytes,
"tailSizeInBytes");
_MTL_PRIVATE_DEF_SEL(tessellationControlPointIndexType,
"tessellationControlPointIndexType");
_MTL_PRIVATE_DEF_SEL(tessellationFactorFormat,
"tessellationFactorFormat");
_MTL_PRIVATE_DEF_SEL(tessellationFactorStepFunction,
"tessellationFactorStepFunction");
_MTL_PRIVATE_DEF_SEL(tessellationOutputWindingOrder,
"tessellationOutputWindingOrder");
_MTL_PRIVATE_DEF_SEL(tessellationPartitionMode,
"tessellationPartitionMode");
_MTL_PRIVATE_DEF_SEL(texture,
"texture");
_MTL_PRIVATE_DEF_SEL(texture2DDescriptorWithPixelFormat_width_height_mipmapped_,
"texture2DDescriptorWithPixelFormat:width:height:mipmapped:");
_MTL_PRIVATE_DEF_SEL(textureBarrier,
"textureBarrier");
_MTL_PRIVATE_DEF_SEL(textureBufferDescriptorWithPixelFormat_width_resourceOptions_usage_,
"textureBufferDescriptorWithPixelFormat:width:resourceOptions:usage:");
_MTL_PRIVATE_DEF_SEL(textureCubeDescriptorWithPixelFormat_size_mipmapped_,
"textureCubeDescriptorWithPixelFormat:size:mipmapped:");
_MTL_PRIVATE_DEF_SEL(textureDataType,
"textureDataType");
_MTL_PRIVATE_DEF_SEL(textureReferenceType,
"textureReferenceType");
_MTL_PRIVATE_DEF_SEL(textureType,
"textureType");
_MTL_PRIVATE_DEF_SEL(threadExecutionWidth,
"threadExecutionWidth");
_MTL_PRIVATE_DEF_SEL(threadGroupSizeIsMultipleOfThreadExecutionWidth,
"threadGroupSizeIsMultipleOfThreadExecutionWidth");
_MTL_PRIVATE_DEF_SEL(threadgroupMemoryAlignment,
"threadgroupMemoryAlignment");
_MTL_PRIVATE_DEF_SEL(threadgroupMemoryDataSize,
"threadgroupMemoryDataSize");
_MTL_PRIVATE_DEF_SEL(threadgroupMemoryLength,
"threadgroupMemoryLength");
_MTL_PRIVATE_DEF_SEL(threadgroupSizeMatchesTileSize,
"threadgroupSizeMatchesTileSize");
_MTL_PRIVATE_DEF_SEL(tileAdditionalBinaryFunctions,
"tileAdditionalBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(tileArguments,
"tileArguments");
_MTL_PRIVATE_DEF_SEL(tileBuffers,
"tileBuffers");
_MTL_PRIVATE_DEF_SEL(tileFunction,
"tileFunction");
_MTL_PRIVATE_DEF_SEL(tileHeight,
"tileHeight");
_MTL_PRIVATE_DEF_SEL(tileWidth,
"tileWidth");
_MTL_PRIVATE_DEF_SEL(triangleCount,
"triangleCount");
_MTL_PRIVATE_DEF_SEL(type,
"type");
_MTL_PRIVATE_DEF_SEL(updateFence_,
"updateFence:");
_MTL_PRIVATE_DEF_SEL(updateFence_afterStages_,
"updateFence:afterStages:");
_MTL_PRIVATE_DEF_SEL(updateTextureMapping_mode_indirectBuffer_indirectBufferOffset_,
"updateTextureMapping:mode:indirectBuffer:indirectBufferOffset:");
_MTL_PRIVATE_DEF_SEL(updateTextureMapping_mode_region_mipLevel_slice_,
"updateTextureMapping:mode:region:mipLevel:slice:");
_MTL_PRIVATE_DEF_SEL(updateTextureMappings_mode_regions_mipLevels_slices_numRegions_,
"updateTextureMappings:mode:regions:mipLevels:slices:numRegions:");
_MTL_PRIVATE_DEF_SEL(url,
"url");
_MTL_PRIVATE_DEF_SEL(usage,
"usage");
_MTL_PRIVATE_DEF_SEL(useHeap_,
"useHeap:");
_MTL_PRIVATE_DEF_SEL(useHeap_stages_,
"useHeap:stages:");
_MTL_PRIVATE_DEF_SEL(useHeaps_count_,
"useHeaps:count:");
_MTL_PRIVATE_DEF_SEL(useHeaps_count_stages_,
"useHeaps:count:stages:");
_MTL_PRIVATE_DEF_SEL(useResource_usage_,
"useResource:usage:");
_MTL_PRIVATE_DEF_SEL(useResource_usage_stages_,
"useResource:usage:stages:");
_MTL_PRIVATE_DEF_SEL(useResources_count_usage_,
"useResources:count:usage:");
_MTL_PRIVATE_DEF_SEL(useResources_count_usage_stages_,
"useResources:count:usage:stages:");
_MTL_PRIVATE_DEF_SEL(usedSize,
"usedSize");
_MTL_PRIVATE_DEF_SEL(vertexAdditionalBinaryFunctions,
"vertexAdditionalBinaryFunctions");
_MTL_PRIVATE_DEF_SEL(vertexArguments,
"vertexArguments");
_MTL_PRIVATE_DEF_SEL(vertexAttributes,
"vertexAttributes");
_MTL_PRIVATE_DEF_SEL(vertexBuffer,
"vertexBuffer");
_MTL_PRIVATE_DEF_SEL(vertexBufferOffset,
"vertexBufferOffset");
_MTL_PRIVATE_DEF_SEL(vertexBuffers,
"vertexBuffers");
_MTL_PRIVATE_DEF_SEL(vertexDescriptor,
"vertexDescriptor");
_MTL_PRIVATE_DEF_SEL(vertexFunction,
"vertexFunction");
_MTL_PRIVATE_DEF_SEL(vertexLinkedFunctions,
"vertexLinkedFunctions");
_MTL_PRIVATE_DEF_SEL(vertexPreloadedLibraries,
"vertexPreloadedLibraries");
_MTL_PRIVATE_DEF_SEL(vertexStride,
"vertexStride");
_MTL_PRIVATE_DEF_SEL(vertical,
"vertical");
_MTL_PRIVATE_DEF_SEL(verticalSampleStorage,
"verticalSampleStorage");
_MTL_PRIVATE_DEF_SEL(visibilityResultBuffer,
"visibilityResultBuffer");
_MTL_PRIVATE_DEF_SEL(visibleFunctionTableDescriptor,
"visibleFunctionTableDescriptor");
_MTL_PRIVATE_DEF_SEL(waitForFence_,
"waitForFence:");
_MTL_PRIVATE_DEF_SEL(waitForFence_beforeStages_,
"waitForFence:beforeStages:");
_MTL_PRIVATE_DEF_SEL(waitUntilCompleted,
"waitUntilCompleted");
_MTL_PRIVATE_DEF_SEL(waitUntilScheduled,
"waitUntilScheduled");
_MTL_PRIVATE_DEF_SEL(width,
"width");
_MTL_PRIVATE_DEF_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_,
"writeCompactedAccelerationStructureSize:toBuffer:offset:");
_MTL_PRIVATE_DEF_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_sizeDataType_,
"writeCompactedAccelerationStructureSize:toBuffer:offset:sizeDataType:");
_MTL_PRIVATE_DEF_SEL(writeMask,
"writeMask");
}
#include <CoreFoundation/CoreFoundation.h>
#include <functional>
namespace MTL
{
class Drawable;
using DrawablePresentedHandler = void (^)(class Drawable*);
using DrawablePresentedHandlerFunction = std::function<void(class Drawable*)>;
class Drawable : public NS::Referencing<Drawable>
{
public:
void addPresentedHandler(const MTL::DrawablePresentedHandlerFunction& function);
void present();
void presentAtTime(CFTimeInterval presentationTime);
void presentAfterMinimumDuration(CFTimeInterval duration);
void addPresentedHandler(const MTL::DrawablePresentedHandler block);
CFTimeInterval presentedTime() const;
NS::UInteger drawableID() const;
};
}
_MTL_INLINE void MTL::Drawable::addPresentedHandler(const MTL::DrawablePresentedHandlerFunction& function)
{
__block DrawablePresentedHandlerFunction blockFunction = function;
addPresentedHandler(^(Drawable* pDrawable) { blockFunction(pDrawable); });
}
_MTL_INLINE void MTL::Drawable::present()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(present));
}
_MTL_INLINE void MTL::Drawable::presentAtTime(CFTimeInterval presentationTime)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentAtTime_), presentationTime);
}
_MTL_INLINE void MTL::Drawable::presentAfterMinimumDuration(CFTimeInterval duration)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentAfterMinimumDuration_), duration);
}
_MTL_INLINE void MTL::Drawable::addPresentedHandler(const MTL::DrawablePresentedHandler block)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addPresentedHandler_), block);
}
_MTL_INLINE CFTimeInterval MTL::Drawable::presentedTime() const
{
return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(presentedTime));
}
_MTL_INLINE NS::UInteger MTL::Drawable::drawableID() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(drawableID));
}
#pragma once
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, PixelFormat) {
PixelFormatInvalid = 0,
PixelFormatA8Unorm = 1,
PixelFormatR8Unorm = 10,
PixelFormatR8Unorm_sRGB = 11,
PixelFormatR8Snorm = 12,
PixelFormatR8Uint = 13,
PixelFormatR8Sint = 14,
PixelFormatR16Unorm = 20,
PixelFormatR16Snorm = 22,
PixelFormatR16Uint = 23,
PixelFormatR16Sint = 24,
PixelFormatR16Float = 25,
PixelFormatRG8Unorm = 30,
PixelFormatRG8Unorm_sRGB = 31,
PixelFormatRG8Snorm = 32,
PixelFormatRG8Uint = 33,
PixelFormatRG8Sint = 34,
PixelFormatB5G6R5Unorm = 40,
PixelFormatA1BGR5Unorm = 41,
PixelFormatABGR4Unorm = 42,
PixelFormatBGR5A1Unorm = 43,
PixelFormatR32Uint = 53,
PixelFormatR32Sint = 54,
PixelFormatR32Float = 55,
PixelFormatRG16Unorm = 60,
PixelFormatRG16Snorm = 62,
PixelFormatRG16Uint = 63,
PixelFormatRG16Sint = 64,
PixelFormatRG16Float = 65,
PixelFormatRGBA8Unorm = 70,
PixelFormatRGBA8Unorm_sRGB = 71,
PixelFormatRGBA8Snorm = 72,
PixelFormatRGBA8Uint = 73,
PixelFormatRGBA8Sint = 74,
PixelFormatBGRA8Unorm = 80,
PixelFormatBGRA8Unorm_sRGB = 81,
PixelFormatRGB10A2Unorm = 90,
PixelFormatRGB10A2Uint = 91,
PixelFormatRG11B10Float = 92,
PixelFormatRGB9E5Float = 93,
PixelFormatBGR10A2Unorm = 94,
PixelFormatRG32Uint = 103,
PixelFormatRG32Sint = 104,
PixelFormatRG32Float = 105,
PixelFormatRGBA16Unorm = 110,
PixelFormatRGBA16Snorm = 112,
PixelFormatRGBA16Uint = 113,
PixelFormatRGBA16Sint = 114,
PixelFormatRGBA16Float = 115,
PixelFormatRGBA32Uint = 123,
PixelFormatRGBA32Sint = 124,
PixelFormatRGBA32Float = 125,
PixelFormatBC1_RGBA = 130,
PixelFormatBC1_RGBA_sRGB = 131,
PixelFormatBC2_RGBA = 132,
PixelFormatBC2_RGBA_sRGB = 133,
PixelFormatBC3_RGBA = 134,
PixelFormatBC3_RGBA_sRGB = 135,
PixelFormatBC4_RUnorm = 140,
PixelFormatBC4_RSnorm = 141,
PixelFormatBC5_RGUnorm = 142,
PixelFormatBC5_RGSnorm = 143,
PixelFormatBC6H_RGBFloat = 150,
PixelFormatBC6H_RGBUfloat = 151,
PixelFormatBC7_RGBAUnorm = 152,
PixelFormatBC7_RGBAUnorm_sRGB = 153,
PixelFormatPVRTC_RGB_2BPP = 160,
PixelFormatPVRTC_RGB_2BPP_sRGB = 161,
PixelFormatPVRTC_RGB_4BPP = 162,
PixelFormatPVRTC_RGB_4BPP_sRGB = 163,
PixelFormatPVRTC_RGBA_2BPP = 164,
PixelFormatPVRTC_RGBA_2BPP_sRGB = 165,
PixelFormatPVRTC_RGBA_4BPP = 166,
PixelFormatPVRTC_RGBA_4BPP_sRGB = 167,
PixelFormatEAC_R11Unorm = 170,
PixelFormatEAC_R11Snorm = 172,
PixelFormatEAC_RG11Unorm = 174,
PixelFormatEAC_RG11Snorm = 176,
PixelFormatEAC_RGBA8 = 178,
PixelFormatEAC_RGBA8_sRGB = 179,
PixelFormatETC2_RGB8 = 180,
PixelFormatETC2_RGB8_sRGB = 181,
PixelFormatETC2_RGB8A1 = 182,
PixelFormatETC2_RGB8A1_sRGB = 183,
PixelFormatASTC_4x4_sRGB = 186,
PixelFormatASTC_5x4_sRGB = 187,
PixelFormatASTC_5x5_sRGB = 188,
PixelFormatASTC_6x5_sRGB = 189,
PixelFormatASTC_6x6_sRGB = 190,
PixelFormatASTC_8x5_sRGB = 192,
PixelFormatASTC_8x6_sRGB = 193,
PixelFormatASTC_8x8_sRGB = 194,
PixelFormatASTC_10x5_sRGB = 195,
PixelFormatASTC_10x6_sRGB = 196,
PixelFormatASTC_10x8_sRGB = 197,
PixelFormatASTC_10x10_sRGB = 198,
PixelFormatASTC_12x10_sRGB = 199,
PixelFormatASTC_12x12_sRGB = 200,
PixelFormatASTC_4x4_LDR = 204,
PixelFormatASTC_5x4_LDR = 205,
PixelFormatASTC_5x5_LDR = 206,
PixelFormatASTC_6x5_LDR = 207,
PixelFormatASTC_6x6_LDR = 208,
PixelFormatASTC_8x5_LDR = 210,
PixelFormatASTC_8x6_LDR = 211,
PixelFormatASTC_8x8_LDR = 212,
PixelFormatASTC_10x5_LDR = 213,
PixelFormatASTC_10x6_LDR = 214,
PixelFormatASTC_10x8_LDR = 215,
PixelFormatASTC_10x10_LDR = 216,
PixelFormatASTC_12x10_LDR = 217,
PixelFormatASTC_12x12_LDR = 218,
PixelFormatASTC_4x4_HDR = 222,
PixelFormatASTC_5x4_HDR = 223,
PixelFormatASTC_5x5_HDR = 224,
PixelFormatASTC_6x5_HDR = 225,
PixelFormatASTC_6x6_HDR = 226,
PixelFormatASTC_8x5_HDR = 228,
PixelFormatASTC_8x6_HDR = 229,
PixelFormatASTC_8x8_HDR = 230,
PixelFormatASTC_10x5_HDR = 231,
PixelFormatASTC_10x6_HDR = 232,
PixelFormatASTC_10x8_HDR = 233,
PixelFormatASTC_10x10_HDR = 234,
PixelFormatASTC_12x10_HDR = 235,
PixelFormatASTC_12x12_HDR = 236,
PixelFormatGBGR422 = 240,
PixelFormatBGRG422 = 241,
PixelFormatDepth16Unorm = 250,
PixelFormatDepth32Float = 252,
PixelFormatStencil8 = 253,
PixelFormatDepth24Unorm_Stencil8 = 255,
PixelFormatDepth32Float_Stencil8 = 260,
PixelFormatX32_Stencil8 = 261,
PixelFormatX24_Stencil8 = 262,
PixelFormatBGRA10_XR = 552,
PixelFormatBGRA10_XR_sRGB = 553,
PixelFormatBGR10_XR = 554,
PixelFormatBGR10_XR_sRGB = 555,
};
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, PurgeableState) {
PurgeableStateKeepCurrent = 1,
PurgeableStateNonVolatile = 2,
PurgeableStateVolatile = 3,
PurgeableStateEmpty = 4,
};
_MTL_ENUM(NS::UInteger, CPUCacheMode) {
CPUCacheModeDefaultCache = 0,
CPUCacheModeWriteCombined = 1,
};
_MTL_ENUM(NS::UInteger, StorageMode) {
StorageModeShared = 0,
StorageModeManaged = 1,
StorageModePrivate = 2,
StorageModeMemoryless = 3,
};
_MTL_ENUM(NS::UInteger, HazardTrackingMode) {
HazardTrackingModeDefault = 0,
HazardTrackingModeUntracked = 1,
HazardTrackingModeTracked = 2,
};
_MTL_OPTIONS(NS::UInteger, ResourceOptions) {
ResourceStorageModeShared = 0,
ResourceHazardTrackingModeDefault = 0,
ResourceCPUCacheModeDefaultCache = 0,
ResourceOptionCPUCacheModeDefault = 0,
ResourceCPUCacheModeWriteCombined = 1,
ResourceOptionCPUCacheModeWriteCombined = 1,
ResourceStorageModeManaged = 16,
ResourceStorageModePrivate = 32,
ResourceStorageModeMemoryless = 48,
ResourceHazardTrackingModeUntracked = 256,
ResourceHazardTrackingModeTracked = 512,
};
class Resource : public NS::Referencing<Resource>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
MTL::CPUCacheMode cpuCacheMode() const;
MTL::StorageMode storageMode() const;
MTL::HazardTrackingMode hazardTrackingMode() const;
MTL::ResourceOptions resourceOptions() const;
MTL::PurgeableState setPurgeableState(MTL::PurgeableState state);
class Heap* heap() const;
NS::UInteger heapOffset() const;
NS::UInteger allocatedSize() const;
void makeAliasable();
bool isAliasable();
};
}
_MTL_INLINE NS::String* MTL::Resource::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Resource::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::Resource::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::CPUCacheMode MTL::Resource::cpuCacheMode() const
{
return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode));
}
_MTL_INLINE MTL::StorageMode MTL::Resource::storageMode() const
{
return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode));
}
_MTL_INLINE MTL::HazardTrackingMode MTL::Resource::hazardTrackingMode() const
{
return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode));
}
_MTL_INLINE MTL::ResourceOptions MTL::Resource::resourceOptions() const
{
return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions));
}
_MTL_INLINE MTL::PurgeableState MTL::Resource::setPurgeableState(MTL::PurgeableState state)
{
return Object::sendMessage<MTL::PurgeableState>(this, _MTL_PRIVATE_SEL(setPurgeableState_), state);
}
_MTL_INLINE MTL::Heap* MTL::Resource::heap() const
{
return Object::sendMessage<MTL::Heap*>(this, _MTL_PRIVATE_SEL(heap));
}
_MTL_INLINE NS::UInteger MTL::Resource::heapOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(heapOffset));
}
_MTL_INLINE NS::UInteger MTL::Resource::allocatedSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(allocatedSize));
}
_MTL_INLINE void MTL::Resource::makeAliasable()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(makeAliasable));
}
_MTL_INLINE bool MTL::Resource::isAliasable()
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAliasable));
}
#pragma once
namespace MTL
{
struct Origin
{
Origin() = default;
Origin(NS::UInteger x, NS::UInteger y, NS::UInteger z);
static Origin Make(NS::UInteger x, NS::UInteger y, NS::UInteger z);
NS::UInteger x;
NS::UInteger y;
NS::UInteger z;
} _MTL_PACKED;
struct Size
{
Size() = default;
Size(NS::UInteger width, NS::UInteger height, NS::UInteger depth);
static Size Make(NS::UInteger width, NS::UInteger height, NS::UInteger depth);
NS::UInteger width;
NS::UInteger height;
NS::UInteger depth;
} _MTL_PACKED;
struct Region
{
Region() = default;
Region(NS::UInteger x, NS::UInteger width);
Region(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height);
Region(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth);
static Region Make1D(NS::UInteger x, NS::UInteger width);
static Region Make2D(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height);
static Region Make3D(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth);
MTL::Origin origin;
MTL::Size size;
} _MTL_PACKED;
struct SamplePosition;
using Coordinate2D = SamplePosition;
struct SamplePosition
{
SamplePosition() = default;
SamplePosition(float _x, float _y);
static SamplePosition Make(float x, float y);
float x;
float y;
} _MTL_PACKED;
}
_MTL_INLINE MTL::Origin::Origin(NS::UInteger _x, NS::UInteger _y, NS::UInteger _z)
: x(_x)
, y(_y)
, z(_z)
{
}
_MTL_INLINE MTL::Origin MTL::Origin::Make(NS::UInteger x, NS::UInteger y, NS::UInteger z)
{
return Origin(x, y, z);
}
_MTL_INLINE MTL::Size::Size(NS::UInteger _width, NS::UInteger _height, NS::UInteger _depth)
: width(_width)
, height(_height)
, depth(_depth)
{
}
_MTL_INLINE MTL::Size MTL::Size::Make(NS::UInteger width, NS::UInteger height, NS::UInteger depth)
{
return Size(width, height, depth);
}
_MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger width)
: origin(x, 0, 0)
, size(width, 1, 1)
{
}
_MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height)
: origin(x, y, 0)
, size(width, height, 1)
{
}
_MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth)
: origin(x, y, z)
, size(width, height, depth)
{
}
_MTL_INLINE MTL::Region MTL::Region::Make1D(NS::UInteger x, NS::UInteger width)
{
return Region(x, width);
}
_MTL_INLINE MTL::Region MTL::Region::Make2D(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height)
{
return Region(x, y, width, height);
}
_MTL_INLINE MTL::Region MTL::Region::Make3D(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth)
{
return Region(x, y, z, width, height, depth);
}
_MTL_INLINE MTL::SamplePosition::SamplePosition(float _x, float _y)
: x(_x)
, y(_y)
{
}
_MTL_INLINE MTL::SamplePosition MTL::SamplePosition::Make(float x, float y)
{
return SamplePosition(x, y);
}
#include <IOSurface/IOSurfaceRef.h>
namespace MTL
{
_MTL_ENUM(NS::UInteger, TextureType) {
TextureType1D = 0,
TextureType1DArray = 1,
TextureType2D = 2,
TextureType2DArray = 3,
TextureType2DMultisample = 4,
TextureTypeCube = 5,
TextureTypeCubeArray = 6,
TextureType3D = 7,
TextureType2DMultisampleArray = 8,
TextureTypeTextureBuffer = 9,
};
_MTL_ENUM(uint8_t, TextureSwizzle) {
TextureSwizzleZero = 0,
TextureSwizzleOne = 1,
TextureSwizzleRed = 2,
TextureSwizzleGreen = 3,
TextureSwizzleBlue = 4,
TextureSwizzleAlpha = 5,
};
struct TextureSwizzleChannels
{
MTL::TextureSwizzle red;
MTL::TextureSwizzle green;
MTL::TextureSwizzle blue;
MTL::TextureSwizzle alpha;
} _MTL_PACKED;
class SharedTextureHandle : public NS::Referencing<SharedTextureHandle>
{
public:
static class SharedTextureHandle* alloc();
class SharedTextureHandle* init();
class Device* device() const;
NS::String* label() const;
};
struct SharedTextureHandlePrivate
{
} _MTL_PACKED;
_MTL_OPTIONS(NS::UInteger, TextureUsage) {
TextureUsageUnknown = 0,
TextureUsageShaderRead = 1,
TextureUsageShaderWrite = 2,
TextureUsageRenderTarget = 4,
TextureUsagePixelFormatView = 16,
};
_MTL_ENUM(NS::Integer, TextureCompressionType) {
TextureCompressionTypeLossless = 0,
TextureCompressionTypeLossy = 1,
};
class TextureDescriptor : public NS::Copying<TextureDescriptor>
{
public:
static class TextureDescriptor* alloc();
class TextureDescriptor* init();
static class TextureDescriptor* texture2DDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, NS::UInteger height, bool mipmapped);
static class TextureDescriptor* textureCubeDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger size, bool mipmapped);
static class TextureDescriptor* textureBufferDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, MTL::ResourceOptions resourceOptions, MTL::TextureUsage usage);
MTL::TextureType textureType() const;
void setTextureType(MTL::TextureType textureType);
MTL::PixelFormat pixelFormat() const;
void setPixelFormat(MTL::PixelFormat pixelFormat);
NS::UInteger width() const;
void setWidth(NS::UInteger width);
NS::UInteger height() const;
void setHeight(NS::UInteger height);
NS::UInteger depth() const;
void setDepth(NS::UInteger depth);
NS::UInteger mipmapLevelCount() const;
void setMipmapLevelCount(NS::UInteger mipmapLevelCount);
NS::UInteger sampleCount() const;
void setSampleCount(NS::UInteger sampleCount);
NS::UInteger arrayLength() const;
void setArrayLength(NS::UInteger arrayLength);
MTL::ResourceOptions resourceOptions() const;
void setResourceOptions(MTL::ResourceOptions resourceOptions);
MTL::CPUCacheMode cpuCacheMode() const;
void setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode);
MTL::StorageMode storageMode() const;
void setStorageMode(MTL::StorageMode storageMode);
MTL::HazardTrackingMode hazardTrackingMode() const;
void setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode);
MTL::TextureUsage usage() const;
void setUsage(MTL::TextureUsage usage);
bool allowGPUOptimizedContents() const;
void setAllowGPUOptimizedContents(bool allowGPUOptimizedContents);
MTL::TextureSwizzleChannels swizzle() const;
void setSwizzle(MTL::TextureSwizzleChannels swizzle);
};
class Texture : public NS::Referencing<Texture, Resource>
{
public:
class Resource* rootResource() const;
class Texture* parentTexture() const;
NS::UInteger parentRelativeLevel() const;
NS::UInteger parentRelativeSlice() const;
class Buffer* buffer() const;
NS::UInteger bufferOffset() const;
NS::UInteger bufferBytesPerRow() const;
IOSurfaceRef iosurface() const;
NS::UInteger iosurfacePlane() const;
MTL::TextureType textureType() const;
MTL::PixelFormat pixelFormat() const;
NS::UInteger width() const;
NS::UInteger height() const;
NS::UInteger depth() const;
NS::UInteger mipmapLevelCount() const;
NS::UInteger sampleCount() const;
NS::UInteger arrayLength() const;
MTL::TextureUsage usage() const;
bool shareable() const;
bool framebufferOnly() const;
NS::UInteger firstMipmapInTail() const;
NS::UInteger tailSizeInBytes() const;
bool isSparse() const;
bool allowGPUOptimizedContents() const;
void getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage, MTL::Region region, NS::UInteger level, NS::UInteger slice);
void replaceRegion(MTL::Region region, NS::UInteger level, NS::UInteger slice, const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage);
void getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, MTL::Region region, NS::UInteger level);
void replaceRegion(MTL::Region region, NS::UInteger level, const void* pixelBytes, NS::UInteger bytesPerRow);
class Texture* newTextureView(MTL::PixelFormat pixelFormat);
class Texture* newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange);
class SharedTextureHandle* newSharedTextureHandle();
class Texture* remoteStorageTexture() const;
class Texture* newRemoteTextureViewForDevice(const class Device* device);
MTL::TextureSwizzleChannels swizzle() const;
class Texture* newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange, MTL::TextureSwizzleChannels swizzle);
};
}
_MTL_INLINE MTL::SharedTextureHandle* MTL::SharedTextureHandle::alloc()
{
return NS::Object::alloc<MTL::SharedTextureHandle>(_MTL_PRIVATE_CLS(MTLSharedTextureHandle));
}
_MTL_INLINE MTL::SharedTextureHandle* MTL::SharedTextureHandle::init()
{
return NS::Object::init<MTL::SharedTextureHandle>();
}
_MTL_INLINE MTL::Device* MTL::SharedTextureHandle::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::SharedTextureHandle::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::alloc()
{
return NS::Object::alloc<MTL::TextureDescriptor>(_MTL_PRIVATE_CLS(MTLTextureDescriptor));
}
_MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::init()
{
return NS::Object::init<MTL::TextureDescriptor>();
}
_MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::texture2DDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, NS::UInteger height, bool mipmapped)
{
return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(texture2DDescriptorWithPixelFormat_width_height_mipmapped_), pixelFormat, width, height, mipmapped);
}
_MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::textureCubeDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger size, bool mipmapped)
{
return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(textureCubeDescriptorWithPixelFormat_size_mipmapped_), pixelFormat, size, mipmapped);
}
_MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::textureBufferDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, MTL::ResourceOptions resourceOptions, MTL::TextureUsage usage)
{
return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(textureBufferDescriptorWithPixelFormat_width_resourceOptions_usage_), pixelFormat, width, resourceOptions, usage);
}
_MTL_INLINE MTL::TextureType MTL::TextureDescriptor::textureType() const
{
return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType));
}
_MTL_INLINE void MTL::TextureDescriptor::setTextureType(MTL::TextureType textureType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextureType_), textureType);
}
_MTL_INLINE MTL::PixelFormat MTL::TextureDescriptor::pixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat));
}
_MTL_INLINE void MTL::TextureDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::width() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(width));
}
_MTL_INLINE void MTL::TextureDescriptor::setWidth(NS::UInteger width)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWidth_), width);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::height() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(height));
}
_MTL_INLINE void MTL::TextureDescriptor::setHeight(NS::UInteger height)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHeight_), height);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::depth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depth));
}
_MTL_INLINE void MTL::TextureDescriptor::setDepth(NS::UInteger depth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepth_), depth);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::mipmapLevelCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(mipmapLevelCount));
}
_MTL_INLINE void MTL::TextureDescriptor::setMipmapLevelCount(NS::UInteger mipmapLevelCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMipmapLevelCount_), mipmapLevelCount);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::sampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE void MTL::TextureDescriptor::setSampleCount(NS::UInteger sampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount);
}
_MTL_INLINE NS::UInteger MTL::TextureDescriptor::arrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength));
}
_MTL_INLINE void MTL::TextureDescriptor::setArrayLength(NS::UInteger arrayLength)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArrayLength_), arrayLength);
}
_MTL_INLINE MTL::ResourceOptions MTL::TextureDescriptor::resourceOptions() const
{
return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions));
}
_MTL_INLINE void MTL::TextureDescriptor::setResourceOptions(MTL::ResourceOptions resourceOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResourceOptions_), resourceOptions);
}
_MTL_INLINE MTL::CPUCacheMode MTL::TextureDescriptor::cpuCacheMode() const
{
return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode));
}
_MTL_INLINE void MTL::TextureDescriptor::setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCpuCacheMode_), cpuCacheMode);
}
_MTL_INLINE MTL::StorageMode MTL::TextureDescriptor::storageMode() const
{
return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode));
}
_MTL_INLINE void MTL::TextureDescriptor::setStorageMode(MTL::StorageMode storageMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode);
}
_MTL_INLINE MTL::HazardTrackingMode MTL::TextureDescriptor::hazardTrackingMode() const
{
return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode));
}
_MTL_INLINE void MTL::TextureDescriptor::setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHazardTrackingMode_), hazardTrackingMode);
}
_MTL_INLINE MTL::TextureUsage MTL::TextureDescriptor::usage() const
{
return Object::sendMessage<MTL::TextureUsage>(this, _MTL_PRIVATE_SEL(usage));
}
_MTL_INLINE void MTL::TextureDescriptor::setUsage(MTL::TextureUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUsage_), usage);
}
_MTL_INLINE bool MTL::TextureDescriptor::allowGPUOptimizedContents() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowGPUOptimizedContents));
}
_MTL_INLINE void MTL::TextureDescriptor::setAllowGPUOptimizedContents(bool allowGPUOptimizedContents)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAllowGPUOptimizedContents_), allowGPUOptimizedContents);
}
_MTL_INLINE MTL::TextureSwizzleChannels MTL::TextureDescriptor::swizzle() const
{
return Object::sendMessage<MTL::TextureSwizzleChannels>(this, _MTL_PRIVATE_SEL(swizzle));
}
_MTL_INLINE void MTL::TextureDescriptor::setSwizzle(MTL::TextureSwizzleChannels swizzle)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSwizzle_), swizzle);
}
_MTL_INLINE MTL::Resource* MTL::Texture::rootResource() const
{
return Object::sendMessage<MTL::Resource*>(this, _MTL_PRIVATE_SEL(rootResource));
}
_MTL_INLINE MTL::Texture* MTL::Texture::parentTexture() const
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(parentTexture));
}
_MTL_INLINE NS::UInteger MTL::Texture::parentRelativeLevel() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(parentRelativeLevel));
}
_MTL_INLINE NS::UInteger MTL::Texture::parentRelativeSlice() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(parentRelativeSlice));
}
_MTL_INLINE MTL::Buffer* MTL::Texture::buffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(buffer));
}
_MTL_INLINE NS::UInteger MTL::Texture::bufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferOffset));
}
_MTL_INLINE NS::UInteger MTL::Texture::bufferBytesPerRow() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferBytesPerRow));
}
_MTL_INLINE IOSurfaceRef MTL::Texture::iosurface() const
{
return Object::sendMessage<IOSurfaceRef>(this, _MTL_PRIVATE_SEL(iosurface));
}
_MTL_INLINE NS::UInteger MTL::Texture::iosurfacePlane() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(iosurfacePlane));
}
_MTL_INLINE MTL::TextureType MTL::Texture::textureType() const
{
return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType));
}
_MTL_INLINE MTL::PixelFormat MTL::Texture::pixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat));
}
_MTL_INLINE NS::UInteger MTL::Texture::width() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(width));
}
_MTL_INLINE NS::UInteger MTL::Texture::height() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(height));
}
_MTL_INLINE NS::UInteger MTL::Texture::depth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depth));
}
_MTL_INLINE NS::UInteger MTL::Texture::mipmapLevelCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(mipmapLevelCount));
}
_MTL_INLINE NS::UInteger MTL::Texture::sampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE NS::UInteger MTL::Texture::arrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength));
}
_MTL_INLINE MTL::TextureUsage MTL::Texture::usage() const
{
return Object::sendMessage<MTL::TextureUsage>(this, _MTL_PRIVATE_SEL(usage));
}
_MTL_INLINE bool MTL::Texture::shareable() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isShareable));
}
_MTL_INLINE bool MTL::Texture::framebufferOnly() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isFramebufferOnly));
}
_MTL_INLINE NS::UInteger MTL::Texture::firstMipmapInTail() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(firstMipmapInTail));
}
_MTL_INLINE NS::UInteger MTL::Texture::tailSizeInBytes() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tailSizeInBytes));
}
_MTL_INLINE bool MTL::Texture::isSparse() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isSparse));
}
_MTL_INLINE bool MTL::Texture::allowGPUOptimizedContents() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowGPUOptimizedContents));
}
_MTL_INLINE void MTL::Texture::getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage, MTL::Region region, NS::UInteger level, NS::UInteger slice)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_), pixelBytes, bytesPerRow, bytesPerImage, region, level, slice);
}
_MTL_INLINE void MTL::Texture::replaceRegion(MTL::Region region, NS::UInteger level, NS::UInteger slice, const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage_), region, level, slice, pixelBytes, bytesPerRow, bytesPerImage);
}
_MTL_INLINE void MTL::Texture::getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, MTL::Region region, NS::UInteger level)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getBytes_bytesPerRow_fromRegion_mipmapLevel_), pixelBytes, bytesPerRow, region, level);
}
_MTL_INLINE void MTL::Texture::replaceRegion(MTL::Region region, NS::UInteger level, const void* pixelBytes, NS::UInteger bytesPerRow)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(replaceRegion_mipmapLevel_withBytes_bytesPerRow_), region, level, pixelBytes, bytesPerRow);
}
_MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_), pixelFormat);
}
_MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_), pixelFormat, textureType, levelRange, sliceRange);
}
_MTL_INLINE MTL::SharedTextureHandle* MTL::Texture::newSharedTextureHandle()
{
return Object::sendMessage<MTL::SharedTextureHandle*>(this, _MTL_PRIVATE_SEL(newSharedTextureHandle));
}
_MTL_INLINE MTL::Texture* MTL::Texture::remoteStorageTexture() const
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(remoteStorageTexture));
}
_MTL_INLINE MTL::Texture* MTL::Texture::newRemoteTextureViewForDevice(const MTL::Device* device)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newRemoteTextureViewForDevice_), device);
}
_MTL_INLINE MTL::TextureSwizzleChannels MTL::Texture::swizzle() const
{
return Object::sendMessage<MTL::TextureSwizzleChannels>(this, _MTL_PRIVATE_SEL(swizzle));
}
_MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange, MTL::TextureSwizzleChannels swizzle)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_swizzle_), pixelFormat, textureType, levelRange, sliceRange, swizzle);
}
#define _CA_EXPORT _NS_EXPORT
#define _CA_EXTERN _NS_EXTERN
#define _CA_INLINE _NS_INLINE
#define _CA_PACKED _NS_PACKED
#define _CA_CONST(type, name) _NS_CONST(type, name)
#define _CA_ENUM(type, name) _NS_ENUM(type, name)
#define _CA_OPTIONS(type, name) _NS_OPTIONS(type, name)
#define _CA_VALIDATE_SIZE(ns, name) _NS_VALIDATE_SIZE(ns, name)
#define _CA_VALIDATE_ENUM(ns, name) _NS_VALIDATE_ENUM(ns, name)
#include <objc/runtime.h>
#define _CA_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol)
#define _CA_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor)
#if defined(CA_PRIVATE_IMPLEMENTATION)
#define _CA_PRIVATE_VISIBILITY __attribute__((visibility("default")))
#define _CA_PRIVATE_IMPORT __attribute__((weak_import))
#if __OBJC__
#define _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol))
#else
#define _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol)
#endif // __OBJC__
#define _CA_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _CA_PRIVATE_VISIBILITY = _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol);
#define _CA_PRIVATE_DEF_PRO(symbol)
#define _CA_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _CA_PRIVATE_VISIBILITY = sel_registerName(symbol);
#define _CA_PRIVATE_DEF_STR(type, symbol) \
_CA_EXTERN type const CA##symbol _CA_PRIVATE_IMPORT; \
type const CA::symbol = (nullptr != &CA##symbol) ? CA##symbol : nullptr;
#else
#define _CA_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol;
#define _CA_PRIVATE_DEF_PRO(symbol)
#define _CA_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor;
#define _CA_PRIVATE_DEF_STR(type, symbol)
#endif // CA_PRIVATE_IMPLEMENTATION
namespace CA
{
namespace Private
{
namespace Class
{
} // Class
} // Private
} // CA
namespace CA
{
namespace Private
{
namespace Protocol
{
_CA_PRIVATE_DEF_PRO(CAMetalDrawable);
} // Protocol
} // Private
} // CA
namespace CA
{
namespace Private
{
namespace Selector
{
_CA_PRIVATE_DEF_SEL(layer,
"layer");
_CA_PRIVATE_DEF_SEL(texture,
"texture");
} // Class
} // Private
} // CA
namespace CA
{
class MetalDrawable : public NS::Referencing<MetalDrawable, MTL::Drawable>
{
public:
class MetalLayer* layer() const;
MTL::Texture* texture() const;
};
}
_CA_INLINE CA::MetalLayer* CA::MetalDrawable::layer() const
{
return Object::sendMessage<MetalLayer*>(this, _MTL_PRIVATE_SEL(layer));
}
_CA_INLINE MTL::Texture* CA::MetalDrawable::texture() const
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(texture));
}
#pragma once
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, AttributeFormat) {
AttributeFormatInvalid = 0,
AttributeFormatUChar2 = 1,
AttributeFormatUChar3 = 2,
AttributeFormatUChar4 = 3,
AttributeFormatChar2 = 4,
AttributeFormatChar3 = 5,
AttributeFormatChar4 = 6,
AttributeFormatUChar2Normalized = 7,
AttributeFormatUChar3Normalized = 8,
AttributeFormatUChar4Normalized = 9,
AttributeFormatChar2Normalized = 10,
AttributeFormatChar3Normalized = 11,
AttributeFormatChar4Normalized = 12,
AttributeFormatUShort2 = 13,
AttributeFormatUShort3 = 14,
AttributeFormatUShort4 = 15,
AttributeFormatShort2 = 16,
AttributeFormatShort3 = 17,
AttributeFormatShort4 = 18,
AttributeFormatUShort2Normalized = 19,
AttributeFormatUShort3Normalized = 20,
AttributeFormatUShort4Normalized = 21,
AttributeFormatShort2Normalized = 22,
AttributeFormatShort3Normalized = 23,
AttributeFormatShort4Normalized = 24,
AttributeFormatHalf2 = 25,
AttributeFormatHalf3 = 26,
AttributeFormatHalf4 = 27,
AttributeFormatFloat = 28,
AttributeFormatFloat2 = 29,
AttributeFormatFloat3 = 30,
AttributeFormatFloat4 = 31,
AttributeFormatInt = 32,
AttributeFormatInt2 = 33,
AttributeFormatInt3 = 34,
AttributeFormatInt4 = 35,
AttributeFormatUInt = 36,
AttributeFormatUInt2 = 37,
AttributeFormatUInt3 = 38,
AttributeFormatUInt4 = 39,
AttributeFormatInt1010102Normalized = 40,
AttributeFormatUInt1010102Normalized = 41,
AttributeFormatUChar4Normalized_BGRA = 42,
AttributeFormatUChar = 45,
AttributeFormatChar = 46,
AttributeFormatUCharNormalized = 47,
AttributeFormatCharNormalized = 48,
AttributeFormatUShort = 49,
AttributeFormatShort = 50,
AttributeFormatUShortNormalized = 51,
AttributeFormatShortNormalized = 52,
AttributeFormatHalf = 53,
};
_MTL_ENUM(NS::UInteger, IndexType) {
IndexTypeUInt16 = 0,
IndexTypeUInt32 = 1,
};
_MTL_ENUM(NS::UInteger, StepFunction) {
StepFunctionConstant = 0,
StepFunctionPerVertex = 1,
StepFunctionPerInstance = 2,
StepFunctionPerPatch = 3,
StepFunctionPerPatchControlPoint = 4,
StepFunctionThreadPositionInGridX = 5,
StepFunctionThreadPositionInGridY = 6,
StepFunctionThreadPositionInGridXIndexed = 7,
StepFunctionThreadPositionInGridYIndexed = 8,
};
class BufferLayoutDescriptor : public NS::Copying<BufferLayoutDescriptor>
{
public:
static class BufferLayoutDescriptor* alloc();
class BufferLayoutDescriptor* init();
NS::UInteger stride() const;
void setStride(NS::UInteger stride);
MTL::StepFunction stepFunction() const;
void setStepFunction(MTL::StepFunction stepFunction);
NS::UInteger stepRate() const;
void setStepRate(NS::UInteger stepRate);
};
class BufferLayoutDescriptorArray : public NS::Referencing<BufferLayoutDescriptorArray>
{
public:
static class BufferLayoutDescriptorArray* alloc();
class BufferLayoutDescriptorArray* init();
class BufferLayoutDescriptor* object(NS::UInteger index);
void setObject(const class BufferLayoutDescriptor* bufferDesc, NS::UInteger index);
};
class AttributeDescriptor : public NS::Copying<AttributeDescriptor>
{
public:
static class AttributeDescriptor* alloc();
class AttributeDescriptor* init();
MTL::AttributeFormat format() const;
void setFormat(MTL::AttributeFormat format);
NS::UInteger offset() const;
void setOffset(NS::UInteger offset);
NS::UInteger bufferIndex() const;
void setBufferIndex(NS::UInteger bufferIndex);
};
class AttributeDescriptorArray : public NS::Referencing<AttributeDescriptorArray>
{
public:
static class AttributeDescriptorArray* alloc();
class AttributeDescriptorArray* init();
class AttributeDescriptor* object(NS::UInteger index);
void setObject(const class AttributeDescriptor* attributeDesc, NS::UInteger index);
};
class StageInputOutputDescriptor : public NS::Copying<StageInputOutputDescriptor>
{
public:
static class StageInputOutputDescriptor* alloc();
class StageInputOutputDescriptor* init();
static class StageInputOutputDescriptor* stageInputOutputDescriptor();
class BufferLayoutDescriptorArray* layouts() const;
class AttributeDescriptorArray* attributes() const;
MTL::IndexType indexType() const;
void setIndexType(MTL::IndexType indexType);
NS::UInteger indexBufferIndex() const;
void setIndexBufferIndex(NS::UInteger indexBufferIndex);
void reset();
};
}
_MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptor::alloc()
{
return NS::Object::alloc<MTL::BufferLayoutDescriptor>(_MTL_PRIVATE_CLS(MTLBufferLayoutDescriptor));
}
_MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptor::init()
{
return NS::Object::init<MTL::BufferLayoutDescriptor>();
}
_MTL_INLINE NS::UInteger MTL::BufferLayoutDescriptor::stride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride));
}
_MTL_INLINE void MTL::BufferLayoutDescriptor::setStride(NS::UInteger stride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStride_), stride);
}
_MTL_INLINE MTL::StepFunction MTL::BufferLayoutDescriptor::stepFunction() const
{
return Object::sendMessage<MTL::StepFunction>(this, _MTL_PRIVATE_SEL(stepFunction));
}
_MTL_INLINE void MTL::BufferLayoutDescriptor::setStepFunction(MTL::StepFunction stepFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepFunction_), stepFunction);
}
_MTL_INLINE NS::UInteger MTL::BufferLayoutDescriptor::stepRate() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stepRate));
}
_MTL_INLINE void MTL::BufferLayoutDescriptor::setStepRate(NS::UInteger stepRate)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepRate_), stepRate);
}
_MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::BufferLayoutDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::BufferLayoutDescriptorArray>(_MTL_PRIVATE_CLS(MTLBufferLayoutDescriptorArray));
}
_MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::BufferLayoutDescriptorArray::init()
{
return NS::Object::init<MTL::BufferLayoutDescriptorArray>();
}
_MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptorArray::object(NS::UInteger index)
{
return Object::sendMessage<MTL::BufferLayoutDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index);
}
_MTL_INLINE void MTL::BufferLayoutDescriptorArray::setObject(const MTL::BufferLayoutDescriptor* bufferDesc, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), bufferDesc, index);
}
_MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptor::alloc()
{
return NS::Object::alloc<MTL::AttributeDescriptor>(_MTL_PRIVATE_CLS(MTLAttributeDescriptor));
}
_MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptor::init()
{
return NS::Object::init<MTL::AttributeDescriptor>();
}
_MTL_INLINE MTL::AttributeFormat MTL::AttributeDescriptor::format() const
{
return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(format));
}
_MTL_INLINE void MTL::AttributeDescriptor::setFormat(MTL::AttributeFormat format)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFormat_), format);
}
_MTL_INLINE NS::UInteger MTL::AttributeDescriptor::offset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset));
}
_MTL_INLINE void MTL::AttributeDescriptor::setOffset(NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset);
}
_MTL_INLINE NS::UInteger MTL::AttributeDescriptor::bufferIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferIndex));
}
_MTL_INLINE void MTL::AttributeDescriptor::setBufferIndex(NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferIndex_), bufferIndex);
}
_MTL_INLINE MTL::AttributeDescriptorArray* MTL::AttributeDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::AttributeDescriptorArray>(_MTL_PRIVATE_CLS(MTLAttributeDescriptorArray));
}
_MTL_INLINE MTL::AttributeDescriptorArray* MTL::AttributeDescriptorArray::init()
{
return NS::Object::init<MTL::AttributeDescriptorArray>();
}
_MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptorArray::object(NS::UInteger index)
{
return Object::sendMessage<MTL::AttributeDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index);
}
_MTL_INLINE void MTL::AttributeDescriptorArray::setObject(const MTL::AttributeDescriptor* attributeDesc, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attributeDesc, index);
}
_MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::alloc()
{
return NS::Object::alloc<MTL::StageInputOutputDescriptor>(_MTL_PRIVATE_CLS(MTLStageInputOutputDescriptor));
}
_MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::init()
{
return NS::Object::init<MTL::StageInputOutputDescriptor>();
}
_MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::stageInputOutputDescriptor()
{
return Object::sendMessage<MTL::StageInputOutputDescriptor*>(_MTL_PRIVATE_CLS(MTLStageInputOutputDescriptor), _MTL_PRIVATE_SEL(stageInputOutputDescriptor));
}
_MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::StageInputOutputDescriptor::layouts() const
{
return Object::sendMessage<MTL::BufferLayoutDescriptorArray*>(this, _MTL_PRIVATE_SEL(layouts));
}
_MTL_INLINE MTL::AttributeDescriptorArray* MTL::StageInputOutputDescriptor::attributes() const
{
return Object::sendMessage<MTL::AttributeDescriptorArray*>(this, _MTL_PRIVATE_SEL(attributes));
}
_MTL_INLINE MTL::IndexType MTL::StageInputOutputDescriptor::indexType() const
{
return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType));
}
_MTL_INLINE void MTL::StageInputOutputDescriptor::setIndexType(MTL::IndexType indexType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType);
}
_MTL_INLINE NS::UInteger MTL::StageInputOutputDescriptor::indexBufferIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferIndex));
}
_MTL_INLINE void MTL::StageInputOutputDescriptor::setIndexBufferIndex(NS::UInteger indexBufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferIndex_), indexBufferIndex);
}
_MTL_INLINE void MTL::StageInputOutputDescriptor::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
namespace MTL
{
struct PackedFloat3
{
PackedFloat3();
PackedFloat3(float x, float y, float z);
float& operator[](int idx);
float operator[](int idx) const;
union
{
struct
{
float x;
float y;
float z;
};
float elements[3];
};
} _MTL_PACKED;
struct PackedFloat4x3
{
PackedFloat4x3();
PackedFloat4x3(const PackedFloat3& col0, const PackedFloat3& col1, const PackedFloat3& col2, const PackedFloat3& col3);
PackedFloat3& operator[](int idx);
const PackedFloat3& operator[](int idx) const;
PackedFloat3 columns[4];
} _MTL_PACKED;
struct AxisAlignedBoundingBox
{
AxisAlignedBoundingBox();
AxisAlignedBoundingBox(PackedFloat3 p);
AxisAlignedBoundingBox(PackedFloat3 min, PackedFloat3 max);
PackedFloat3 min;
PackedFloat3 max;
} _MTL_PACKED;
}
_MTL_INLINE MTL::PackedFloat3::PackedFloat3()
: x(0.0f)
, y(0.0f)
, z(0.0f)
{
}
_MTL_INLINE MTL::PackedFloat3::PackedFloat3(float _x, float _y, float _z)
: x(_x)
, y(_y)
, z(_z)
{
}
_MTL_INLINE float& MTL::PackedFloat3::operator[](int idx)
{
return elements[idx];
}
_MTL_INLINE float MTL::PackedFloat3::operator[](int idx) const
{
return elements[idx];
}
_MTL_INLINE MTL::PackedFloat4x3::PackedFloat4x3()
{
columns[0] = PackedFloat3(0.0f, 0.0f, 0.0f);
columns[1] = PackedFloat3(0.0f, 0.0f, 0.0f);
columns[2] = PackedFloat3(0.0f, 0.0f, 0.0f);
columns[3] = PackedFloat3(0.0f, 0.0f, 0.0f);
}
_MTL_INLINE MTL::PackedFloat4x3::PackedFloat4x3(const PackedFloat3& col0, const PackedFloat3& col1, const PackedFloat3& col2, const PackedFloat3& col3)
{
columns[0] = col0;
columns[1] = col1;
columns[2] = col2;
columns[3] = col3;
}
_MTL_INLINE MTL::PackedFloat3& MTL::PackedFloat4x3::operator[](int idx)
{
return columns[idx];
}
_MTL_INLINE const MTL::PackedFloat3& MTL::PackedFloat4x3::operator[](int idx) const
{
return columns[idx];
}
_MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox()
: min(INFINITY, INFINITY, INFINITY)
, max(-INFINITY, -INFINITY, -INFINITY)
{
}
_MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox(PackedFloat3 p)
: min(p)
, max(p)
{
}
_MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox(PackedFloat3 _min, PackedFloat3 _max)
: min(_min)
, max(_max)
{
}
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, AccelerationStructureUsage) {
AccelerationStructureUsageNone = 0,
AccelerationStructureUsageRefit = 1,
AccelerationStructureUsagePreferFastBuild = 2,
AccelerationStructureUsageExtendedLimits = 4,
};
_MTL_OPTIONS(uint32_t, AccelerationStructureInstanceOptions) {
AccelerationStructureInstanceOptionNone = 0,
AccelerationStructureInstanceOptionDisableTriangleCulling = 1,
AccelerationStructureInstanceOptionTriangleFrontFacingWindingCounterClockwise = 2,
AccelerationStructureInstanceOptionOpaque = 4,
AccelerationStructureInstanceOptionNonOpaque = 8,
};
class AccelerationStructureDescriptor : public NS::Copying<AccelerationStructureDescriptor>
{
public:
static class AccelerationStructureDescriptor* alloc();
class AccelerationStructureDescriptor* init();
MTL::AccelerationStructureUsage usage() const;
void setUsage(MTL::AccelerationStructureUsage usage);
};
class AccelerationStructureGeometryDescriptor : public NS::Copying<AccelerationStructureGeometryDescriptor>
{
public:
static class AccelerationStructureGeometryDescriptor* alloc();
class AccelerationStructureGeometryDescriptor* init();
NS::UInteger intersectionFunctionTableOffset() const;
void setIntersectionFunctionTableOffset(NS::UInteger intersectionFunctionTableOffset);
bool opaque() const;
void setOpaque(bool opaque);
bool allowDuplicateIntersectionFunctionInvocation() const;
void setAllowDuplicateIntersectionFunctionInvocation(bool allowDuplicateIntersectionFunctionInvocation);
NS::String* label() const;
void setLabel(const NS::String* label);
};
_MTL_ENUM(uint32_t, MotionBorderMode) {
MotionBorderModeClamp = 0,
MotionBorderModeVanish = 1,
};
class PrimitiveAccelerationStructureDescriptor : public NS::Copying<PrimitiveAccelerationStructureDescriptor, MTL::AccelerationStructureDescriptor>
{
public:
static class PrimitiveAccelerationStructureDescriptor* alloc();
class PrimitiveAccelerationStructureDescriptor* init();
NS::Array* geometryDescriptors() const;
void setGeometryDescriptors(const NS::Array* geometryDescriptors);
MTL::MotionBorderMode motionStartBorderMode() const;
void setMotionStartBorderMode(MTL::MotionBorderMode motionStartBorderMode);
MTL::MotionBorderMode motionEndBorderMode() const;
void setMotionEndBorderMode(MTL::MotionBorderMode motionEndBorderMode);
float motionStartTime() const;
void setMotionStartTime(float motionStartTime);
float motionEndTime() const;
void setMotionEndTime(float motionEndTime);
NS::UInteger motionKeyframeCount() const;
void setMotionKeyframeCount(NS::UInteger motionKeyframeCount);
static MTL::PrimitiveAccelerationStructureDescriptor* descriptor();
};
class AccelerationStructureTriangleGeometryDescriptor : public NS::Copying<AccelerationStructureTriangleGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor>
{
public:
static class AccelerationStructureTriangleGeometryDescriptor* alloc();
class AccelerationStructureTriangleGeometryDescriptor* init();
class Buffer* vertexBuffer() const;
void setVertexBuffer(const class Buffer* vertexBuffer);
NS::UInteger vertexBufferOffset() const;
void setVertexBufferOffset(NS::UInteger vertexBufferOffset);
NS::UInteger vertexStride() const;
void setVertexStride(NS::UInteger vertexStride);
class Buffer* indexBuffer() const;
void setIndexBuffer(const class Buffer* indexBuffer);
NS::UInteger indexBufferOffset() const;
void setIndexBufferOffset(NS::UInteger indexBufferOffset);
MTL::IndexType indexType() const;
void setIndexType(MTL::IndexType indexType);
NS::UInteger triangleCount() const;
void setTriangleCount(NS::UInteger triangleCount);
static MTL::AccelerationStructureTriangleGeometryDescriptor* descriptor();
};
class AccelerationStructureBoundingBoxGeometryDescriptor : public NS::Copying<AccelerationStructureBoundingBoxGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor>
{
public:
static class AccelerationStructureBoundingBoxGeometryDescriptor* alloc();
class AccelerationStructureBoundingBoxGeometryDescriptor* init();
class Buffer* boundingBoxBuffer() const;
void setBoundingBoxBuffer(const class Buffer* boundingBoxBuffer);
NS::UInteger boundingBoxBufferOffset() const;
void setBoundingBoxBufferOffset(NS::UInteger boundingBoxBufferOffset);
NS::UInteger boundingBoxStride() const;
void setBoundingBoxStride(NS::UInteger boundingBoxStride);
NS::UInteger boundingBoxCount() const;
void setBoundingBoxCount(NS::UInteger boundingBoxCount);
static MTL::AccelerationStructureBoundingBoxGeometryDescriptor* descriptor();
};
class MotionKeyframeData : public NS::Referencing<MotionKeyframeData>
{
public:
static class MotionKeyframeData* alloc();
class MotionKeyframeData* init();
class Buffer* buffer() const;
void setBuffer(const class Buffer* buffer);
NS::UInteger offset() const;
void setOffset(NS::UInteger offset);
static MTL::MotionKeyframeData* data();
};
class AccelerationStructureMotionTriangleGeometryDescriptor : public NS::Copying<AccelerationStructureMotionTriangleGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor>
{
public:
static class AccelerationStructureMotionTriangleGeometryDescriptor* alloc();
class AccelerationStructureMotionTriangleGeometryDescriptor* init();
NS::Array* vertexBuffers() const;
void setVertexBuffers(const NS::Array* vertexBuffers);
NS::UInteger vertexStride() const;
void setVertexStride(NS::UInteger vertexStride);
class Buffer* indexBuffer() const;
void setIndexBuffer(const class Buffer* indexBuffer);
NS::UInteger indexBufferOffset() const;
void setIndexBufferOffset(NS::UInteger indexBufferOffset);
MTL::IndexType indexType() const;
void setIndexType(MTL::IndexType indexType);
NS::UInteger triangleCount() const;
void setTriangleCount(NS::UInteger triangleCount);
static MTL::AccelerationStructureMotionTriangleGeometryDescriptor* descriptor();
};
class AccelerationStructureMotionBoundingBoxGeometryDescriptor : public NS::Copying<AccelerationStructureMotionBoundingBoxGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor>
{
public:
static class AccelerationStructureMotionBoundingBoxGeometryDescriptor* alloc();
class AccelerationStructureMotionBoundingBoxGeometryDescriptor* init();
NS::Array* boundingBoxBuffers() const;
void setBoundingBoxBuffers(const NS::Array* boundingBoxBuffers);
NS::UInteger boundingBoxStride() const;
void setBoundingBoxStride(NS::UInteger boundingBoxStride);
NS::UInteger boundingBoxCount() const;
void setBoundingBoxCount(NS::UInteger boundingBoxCount);
static MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* descriptor();
};
struct AccelerationStructureInstanceDescriptor
{
MTL::PackedFloat4x3 transformationMatrix;
MTL::AccelerationStructureInstanceOptions options;
uint32_t mask;
uint32_t intersectionFunctionTableOffset;
uint32_t accelerationStructureIndex;
} _MTL_PACKED;
struct AccelerationStructureUserIDInstanceDescriptor
{
MTL::PackedFloat4x3 transformationMatrix;
MTL::AccelerationStructureInstanceOptions options;
uint32_t mask;
uint32_t intersectionFunctionTableOffset;
uint32_t accelerationStructureIndex;
uint32_t userID;
} _MTL_PACKED;
_MTL_ENUM(NS::UInteger, AccelerationStructureInstanceDescriptorType) {
AccelerationStructureInstanceDescriptorTypeDefault = 0,
AccelerationStructureInstanceDescriptorTypeUserID = 1,
AccelerationStructureInstanceDescriptorTypeMotion = 2,
};
struct AccelerationStructureMotionInstanceDescriptor
{
MTL::AccelerationStructureInstanceOptions options;
uint32_t mask;
uint32_t intersectionFunctionTableOffset;
uint32_t accelerationStructureIndex;
uint32_t userID;
uint32_t motionTransformsStartIndex;
uint32_t motionTransformsCount;
MTL::MotionBorderMode motionStartBorderMode;
MTL::MotionBorderMode motionEndBorderMode;
float motionStartTime;
float motionEndTime;
} _MTL_PACKED;
class InstanceAccelerationStructureDescriptor : public NS::Copying<InstanceAccelerationStructureDescriptor, MTL::AccelerationStructureDescriptor>
{
public:
static class InstanceAccelerationStructureDescriptor* alloc();
class InstanceAccelerationStructureDescriptor* init();
class Buffer* instanceDescriptorBuffer() const;
void setInstanceDescriptorBuffer(const class Buffer* instanceDescriptorBuffer);
NS::UInteger instanceDescriptorBufferOffset() const;
void setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset);
NS::UInteger instanceDescriptorStride() const;
void setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride);
NS::UInteger instanceCount() const;
void setInstanceCount(NS::UInteger instanceCount);
NS::Array* instancedAccelerationStructures() const;
void setInstancedAccelerationStructures(const NS::Array* instancedAccelerationStructures);
MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType() const;
void setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType);
class Buffer* motionTransformBuffer() const;
void setMotionTransformBuffer(const class Buffer* motionTransformBuffer);
NS::UInteger motionTransformBufferOffset() const;
void setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset);
NS::UInteger motionTransformCount() const;
void setMotionTransformCount(NS::UInteger motionTransformCount);
static MTL::InstanceAccelerationStructureDescriptor* descriptor();
};
class AccelerationStructure : public NS::Referencing<AccelerationStructure, Resource>
{
public:
NS::UInteger size() const;
};
}
_MTL_INLINE MTL::AccelerationStructureDescriptor* MTL::AccelerationStructureDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureDescriptor* MTL::AccelerationStructureDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureDescriptor>();
}
_MTL_INLINE MTL::AccelerationStructureUsage MTL::AccelerationStructureDescriptor::usage() const
{
return Object::sendMessage<MTL::AccelerationStructureUsage>(this, _MTL_PRIVATE_SEL(usage));
}
_MTL_INLINE void MTL::AccelerationStructureDescriptor::setUsage(MTL::AccelerationStructureUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUsage_), usage);
}
_MTL_INLINE MTL::AccelerationStructureGeometryDescriptor* MTL::AccelerationStructureGeometryDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureGeometryDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureGeometryDescriptor* MTL::AccelerationStructureGeometryDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureGeometryDescriptor>();
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureGeometryDescriptor::intersectionFunctionTableOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(intersectionFunctionTableOffset));
}
_MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setIntersectionFunctionTableOffset(NS::UInteger intersectionFunctionTableOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTableOffset_), intersectionFunctionTableOffset);
}
_MTL_INLINE bool MTL::AccelerationStructureGeometryDescriptor::opaque() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(opaque));
}
_MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setOpaque(bool opaque)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaque_), opaque);
}
_MTL_INLINE bool MTL::AccelerationStructureGeometryDescriptor::allowDuplicateIntersectionFunctionInvocation() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowDuplicateIntersectionFunctionInvocation));
}
_MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setAllowDuplicateIntersectionFunctionInvocation(bool allowDuplicateIntersectionFunctionInvocation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAllowDuplicateIntersectionFunctionInvocation_), allowDuplicateIntersectionFunctionInvocation);
}
_MTL_INLINE NS::String* MTL::AccelerationStructureGeometryDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::alloc()
{
return NS::Object::alloc<MTL::PrimitiveAccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLPrimitiveAccelerationStructureDescriptor));
}
_MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::init()
{
return NS::Object::init<MTL::PrimitiveAccelerationStructureDescriptor>();
}
_MTL_INLINE NS::Array* MTL::PrimitiveAccelerationStructureDescriptor::geometryDescriptors() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(geometryDescriptors));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setGeometryDescriptors(const NS::Array* geometryDescriptors)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setGeometryDescriptors_), geometryDescriptors);
}
_MTL_INLINE MTL::MotionBorderMode MTL::PrimitiveAccelerationStructureDescriptor::motionStartBorderMode() const
{
return Object::sendMessage<MTL::MotionBorderMode>(this, _MTL_PRIVATE_SEL(motionStartBorderMode));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionStartBorderMode(MTL::MotionBorderMode motionStartBorderMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionStartBorderMode_), motionStartBorderMode);
}
_MTL_INLINE MTL::MotionBorderMode MTL::PrimitiveAccelerationStructureDescriptor::motionEndBorderMode() const
{
return Object::sendMessage<MTL::MotionBorderMode>(this, _MTL_PRIVATE_SEL(motionEndBorderMode));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionEndBorderMode(MTL::MotionBorderMode motionEndBorderMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionEndBorderMode_), motionEndBorderMode);
}
_MTL_INLINE float MTL::PrimitiveAccelerationStructureDescriptor::motionStartTime() const
{
return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(motionStartTime));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionStartTime(float motionStartTime)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionStartTime_), motionStartTime);
}
_MTL_INLINE float MTL::PrimitiveAccelerationStructureDescriptor::motionEndTime() const
{
return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(motionEndTime));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionEndTime(float motionEndTime)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionEndTime_), motionEndTime);
}
_MTL_INLINE NS::UInteger MTL::PrimitiveAccelerationStructureDescriptor::motionKeyframeCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionKeyframeCount));
}
_MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionKeyframeCount(NS::UInteger motionKeyframeCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionKeyframeCount_), motionKeyframeCount);
}
_MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::descriptor()
{
return Object::sendMessage<MTL::PrimitiveAccelerationStructureDescriptor*>(_MTL_PRIVATE_CLS(MTLPrimitiveAccelerationStructureDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureTriangleGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureTriangleGeometryDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureTriangleGeometryDescriptor>();
}
_MTL_INLINE MTL::Buffer* MTL::AccelerationStructureTriangleGeometryDescriptor::vertexBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(vertexBuffer));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexBuffer(const MTL::Buffer* vertexBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_), vertexBuffer);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::vertexBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexBufferOffset));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexBufferOffset(NS::UInteger vertexBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBufferOffset_), vertexBufferOffset);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::vertexStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexStride));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexStride(NS::UInteger vertexStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexStride_), vertexStride);
}
_MTL_INLINE MTL::Buffer* MTL::AccelerationStructureTriangleGeometryDescriptor::indexBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::indexBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset);
}
_MTL_INLINE MTL::IndexType MTL::AccelerationStructureTriangleGeometryDescriptor::indexType() const
{
return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexType(MTL::IndexType indexType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::triangleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(triangleCount));
}
_MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setTriangleCount(NS::UInteger triangleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleCount_), triangleCount);
}
_MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::descriptor()
{
return Object::sendMessage<MTL::AccelerationStructureTriangleGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureTriangleGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureBoundingBoxGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureBoundingBoxGeometryDescriptor>();
}
_MTL_INLINE MTL::Buffer* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(boundingBoxBuffer));
}
_MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxBuffer(const MTL::Buffer* boundingBoxBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBuffer_), boundingBoxBuffer);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxBufferOffset));
}
_MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxBufferOffset(NS::UInteger boundingBoxBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBufferOffset_), boundingBoxBufferOffset);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxStride));
}
_MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxStride(NS::UInteger boundingBoxStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxStride_), boundingBoxStride);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxCount));
}
_MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxCount(NS::UInteger boundingBoxCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxCount_), boundingBoxCount);
}
_MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::descriptor()
{
return Object::sendMessage<MTL::AccelerationStructureBoundingBoxGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::alloc()
{
return NS::Object::alloc<MTL::MotionKeyframeData>(_MTL_PRIVATE_CLS(MTLMotionKeyframeData));
}
_MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::init()
{
return NS::Object::init<MTL::MotionKeyframeData>();
}
_MTL_INLINE MTL::Buffer* MTL::MotionKeyframeData::buffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(buffer));
}
_MTL_INLINE void MTL::MotionKeyframeData::setBuffer(const MTL::Buffer* buffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_), buffer);
}
_MTL_INLINE NS::UInteger MTL::MotionKeyframeData::offset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset));
}
_MTL_INLINE void MTL::MotionKeyframeData::setOffset(NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset);
}
_MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::data()
{
return Object::sendMessage<MTL::MotionKeyframeData*>(_MTL_PRIVATE_CLS(MTLMotionKeyframeData), _MTL_PRIVATE_SEL(data));
}
_MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureMotionTriangleGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureMotionTriangleGeometryDescriptor>();
}
_MTL_INLINE NS::Array* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::vertexBuffers() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexBuffers));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setVertexBuffers(const NS::Array* vertexBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffers_), vertexBuffers);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::vertexStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexStride));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setVertexStride(NS::UInteger vertexStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexStride_), vertexStride);
}
_MTL_INLINE MTL::Buffer* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset);
}
_MTL_INLINE MTL::IndexType MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexType() const
{
return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexType(MTL::IndexType indexType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::triangleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(triangleCount));
}
_MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setTriangleCount(NS::UInteger triangleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleCount_), triangleCount);
}
_MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::descriptor()
{
return Object::sendMessage<MTL::AccelerationStructureMotionTriangleGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::alloc()
{
return NS::Object::alloc<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor));
}
_MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::init()
{
return NS::Object::init<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor>();
}
_MTL_INLINE NS::Array* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxBuffers() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(boundingBoxBuffers));
}
_MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxBuffers(const NS::Array* boundingBoxBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBuffers_), boundingBoxBuffers);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxStride));
}
_MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxStride(NS::UInteger boundingBoxStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxStride_), boundingBoxStride);
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxCount));
}
_MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxCount(NS::UInteger boundingBoxCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxCount_), boundingBoxCount);
}
_MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::descriptor()
{
return Object::sendMessage<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::alloc()
{
return NS::Object::alloc<MTL::InstanceAccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLInstanceAccelerationStructureDescriptor));
}
_MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::init()
{
return NS::Object::init<MTL::InstanceAccelerationStructureDescriptor>();
}
_MTL_INLINE MTL::Buffer* MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(instanceDescriptorBuffer));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorBuffer(const MTL::Buffer* instanceDescriptorBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBuffer_), instanceDescriptorBuffer);
}
_MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorBufferOffset));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBufferOffset_), instanceDescriptorBufferOffset);
}
_MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorStride));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorStride_), instanceDescriptorStride);
}
_MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceCount));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceCount(NS::UInteger instanceCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceCount_), instanceCount);
}
_MTL_INLINE NS::Array* MTL::InstanceAccelerationStructureDescriptor::instancedAccelerationStructures() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(instancedAccelerationStructures));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstancedAccelerationStructures(const NS::Array* instancedAccelerationStructures)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstancedAccelerationStructures_), instancedAccelerationStructures);
}
_MTL_INLINE MTL::AccelerationStructureInstanceDescriptorType MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorType() const
{
return Object::sendMessage<MTL::AccelerationStructureInstanceDescriptorType>(this, _MTL_PRIVATE_SEL(instanceDescriptorType));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorType_), instanceDescriptorType);
}
_MTL_INLINE MTL::Buffer* MTL::InstanceAccelerationStructureDescriptor::motionTransformBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(motionTransformBuffer));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformBuffer(const MTL::Buffer* motionTransformBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBuffer_), motionTransformBuffer);
}
_MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::motionTransformBufferOffset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformBufferOffset));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBufferOffset_), motionTransformBufferOffset);
}
_MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::motionTransformCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformCount));
}
_MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformCount(NS::UInteger motionTransformCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformCount_), motionTransformCount);
}
_MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::descriptor()
{
return Object::sendMessage<MTL::InstanceAccelerationStructureDescriptor*>(_MTL_PRIVATE_CLS(MTLInstanceAccelerationStructureDescriptor), _MTL_PRIVATE_SEL(descriptor));
}
_MTL_INLINE NS::UInteger MTL::AccelerationStructure::size() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size));
}
#pragma once
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, DataType) {
DataTypeNone = 0,
DataTypeStruct = 1,
DataTypeArray = 2,
DataTypeFloat = 3,
DataTypeFloat2 = 4,
DataTypeFloat3 = 5,
DataTypeFloat4 = 6,
DataTypeFloat2x2 = 7,
DataTypeFloat2x3 = 8,
DataTypeFloat2x4 = 9,
DataTypeFloat3x2 = 10,
DataTypeFloat3x3 = 11,
DataTypeFloat3x4 = 12,
DataTypeFloat4x2 = 13,
DataTypeFloat4x3 = 14,
DataTypeFloat4x4 = 15,
DataTypeHalf = 16,
DataTypeHalf2 = 17,
DataTypeHalf3 = 18,
DataTypeHalf4 = 19,
DataTypeHalf2x2 = 20,
DataTypeHalf2x3 = 21,
DataTypeHalf2x4 = 22,
DataTypeHalf3x2 = 23,
DataTypeHalf3x3 = 24,
DataTypeHalf3x4 = 25,
DataTypeHalf4x2 = 26,
DataTypeHalf4x3 = 27,
DataTypeHalf4x4 = 28,
DataTypeInt = 29,
DataTypeInt2 = 30,
DataTypeInt3 = 31,
DataTypeInt4 = 32,
DataTypeUInt = 33,
DataTypeUInt2 = 34,
DataTypeUInt3 = 35,
DataTypeUInt4 = 36,
DataTypeShort = 37,
DataTypeShort2 = 38,
DataTypeShort3 = 39,
DataTypeShort4 = 40,
DataTypeUShort = 41,
DataTypeUShort2 = 42,
DataTypeUShort3 = 43,
DataTypeUShort4 = 44,
DataTypeChar = 45,
DataTypeChar2 = 46,
DataTypeChar3 = 47,
DataTypeChar4 = 48,
DataTypeUChar = 49,
DataTypeUChar2 = 50,
DataTypeUChar3 = 51,
DataTypeUChar4 = 52,
DataTypeBool = 53,
DataTypeBool2 = 54,
DataTypeBool3 = 55,
DataTypeBool4 = 56,
DataTypeTexture = 58,
DataTypeSampler = 59,
DataTypePointer = 60,
DataTypeR8Unorm = 62,
DataTypeR8Snorm = 63,
DataTypeR16Unorm = 64,
DataTypeR16Snorm = 65,
DataTypeRG8Unorm = 66,
DataTypeRG8Snorm = 67,
DataTypeRG16Unorm = 68,
DataTypeRG16Snorm = 69,
DataTypeRGBA8Unorm = 70,
DataTypeRGBA8Unorm_sRGB = 71,
DataTypeRGBA8Snorm = 72,
DataTypeRGBA16Unorm = 73,
DataTypeRGBA16Snorm = 74,
DataTypeRGB10A2Unorm = 75,
DataTypeRG11B10Float = 76,
DataTypeRGB9E5Float = 77,
DataTypeRenderPipeline = 78,
DataTypeComputePipeline = 79,
DataTypeIndirectCommandBuffer = 80,
DataTypeLong = 81,
DataTypeLong2 = 82,
DataTypeLong3 = 83,
DataTypeLong4 = 84,
DataTypeULong = 85,
DataTypeULong2 = 86,
DataTypeULong3 = 87,
DataTypeULong4 = 88,
DataTypeVisibleFunctionTable = 115,
DataTypeIntersectionFunctionTable = 116,
DataTypePrimitiveAccelerationStructure = 117,
DataTypeInstanceAccelerationStructure = 118,
};
_MTL_ENUM(NS::UInteger, ArgumentType) {
ArgumentTypeBuffer = 0,
ArgumentTypeThreadgroupMemory = 1,
ArgumentTypeTexture = 2,
ArgumentTypeSampler = 3,
ArgumentTypeImageblockData = 16,
ArgumentTypeImageblock = 17,
ArgumentTypeVisibleFunctionTable = 24,
ArgumentTypePrimitiveAccelerationStructure = 25,
ArgumentTypeInstanceAccelerationStructure = 26,
ArgumentTypeIntersectionFunctionTable = 27,
};
_MTL_ENUM(NS::UInteger, ArgumentAccess) {
ArgumentAccessReadOnly = 0,
ArgumentAccessReadWrite = 1,
ArgumentAccessWriteOnly = 2,
};
class Type : public NS::Referencing<Type>
{
public:
static class Type* alloc();
class Type* init();
MTL::DataType dataType() const;
};
class StructMember : public NS::Referencing<StructMember>
{
public:
static class StructMember* alloc();
class StructMember* init();
NS::String* name() const;
NS::UInteger offset() const;
MTL::DataType dataType() const;
class StructType* structType();
class ArrayType* arrayType();
class TextureReferenceType* textureReferenceType();
class PointerType* pointerType();
NS::UInteger argumentIndex() const;
};
class StructType : public NS::Referencing<StructType, Type>
{
public:
static class StructType* alloc();
class StructType* init();
NS::Array* members() const;
class StructMember* memberByName(const NS::String* name);
};
class ArrayType : public NS::Referencing<ArrayType, Type>
{
public:
static class ArrayType* alloc();
class ArrayType* init();
MTL::DataType elementType() const;
NS::UInteger arrayLength() const;
NS::UInteger stride() const;
NS::UInteger argumentIndexStride() const;
class StructType* elementStructType();
class ArrayType* elementArrayType();
class TextureReferenceType* elementTextureReferenceType();
class PointerType* elementPointerType();
};
class PointerType : public NS::Referencing<PointerType, Type>
{
public:
static class PointerType* alloc();
class PointerType* init();
MTL::DataType elementType() const;
MTL::ArgumentAccess access() const;
NS::UInteger alignment() const;
NS::UInteger dataSize() const;
bool elementIsArgumentBuffer() const;
class StructType* elementStructType();
class ArrayType* elementArrayType();
};
class TextureReferenceType : public NS::Referencing<TextureReferenceType, Type>
{
public:
static class TextureReferenceType* alloc();
class TextureReferenceType* init();
MTL::DataType textureDataType() const;
MTL::TextureType textureType() const;
MTL::ArgumentAccess access() const;
bool isDepthTexture() const;
};
class Argument : public NS::Referencing<Argument>
{
public:
static class Argument* alloc();
class Argument* init();
NS::String* name() const;
MTL::ArgumentType type() const;
MTL::ArgumentAccess access() const;
NS::UInteger index() const;
bool active() const;
NS::UInteger bufferAlignment() const;
NS::UInteger bufferDataSize() const;
MTL::DataType bufferDataType() const;
class StructType* bufferStructType() const;
class PointerType* bufferPointerType() const;
NS::UInteger threadgroupMemoryAlignment() const;
NS::UInteger threadgroupMemoryDataSize() const;
MTL::TextureType textureType() const;
MTL::DataType textureDataType() const;
bool isDepthTexture() const;
NS::UInteger arrayLength() const;
};
}
_MTL_INLINE MTL::Type* MTL::Type::alloc()
{
return NS::Object::alloc<MTL::Type>(_MTL_PRIVATE_CLS(MTLType));
}
_MTL_INLINE MTL::Type* MTL::Type::init()
{
return NS::Object::init<MTL::Type>();
}
_MTL_INLINE MTL::DataType MTL::Type::dataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType));
}
_MTL_INLINE MTL::StructMember* MTL::StructMember::alloc()
{
return NS::Object::alloc<MTL::StructMember>(_MTL_PRIVATE_CLS(MTLStructMember));
}
_MTL_INLINE MTL::StructMember* MTL::StructMember::init()
{
return NS::Object::init<MTL::StructMember>();
}
_MTL_INLINE NS::String* MTL::StructMember::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::UInteger MTL::StructMember::offset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset));
}
_MTL_INLINE MTL::DataType MTL::StructMember::dataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType));
}
_MTL_INLINE MTL::StructType* MTL::StructMember::structType()
{
return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(structType));
}
_MTL_INLINE MTL::ArrayType* MTL::StructMember::arrayType()
{
return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(arrayType));
}
_MTL_INLINE MTL::TextureReferenceType* MTL::StructMember::textureReferenceType()
{
return Object::sendMessage<MTL::TextureReferenceType*>(this, _MTL_PRIVATE_SEL(textureReferenceType));
}
_MTL_INLINE MTL::PointerType* MTL::StructMember::pointerType()
{
return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(pointerType));
}
_MTL_INLINE NS::UInteger MTL::StructMember::argumentIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndex));
}
_MTL_INLINE MTL::StructType* MTL::StructType::alloc()
{
return NS::Object::alloc<MTL::StructType>(_MTL_PRIVATE_CLS(MTLStructType));
}
_MTL_INLINE MTL::StructType* MTL::StructType::init()
{
return NS::Object::init<MTL::StructType>();
}
_MTL_INLINE NS::Array* MTL::StructType::members() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(members));
}
_MTL_INLINE MTL::StructMember* MTL::StructType::memberByName(const NS::String* name)
{
return Object::sendMessage<MTL::StructMember*>(this, _MTL_PRIVATE_SEL(memberByName_), name);
}
_MTL_INLINE MTL::ArrayType* MTL::ArrayType::alloc()
{
return NS::Object::alloc<MTL::ArrayType>(_MTL_PRIVATE_CLS(MTLArrayType));
}
_MTL_INLINE MTL::ArrayType* MTL::ArrayType::init()
{
return NS::Object::init<MTL::ArrayType>();
}
_MTL_INLINE MTL::DataType MTL::ArrayType::elementType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(elementType));
}
_MTL_INLINE NS::UInteger MTL::ArrayType::arrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength));
}
_MTL_INLINE NS::UInteger MTL::ArrayType::stride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride));
}
_MTL_INLINE NS::UInteger MTL::ArrayType::argumentIndexStride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndexStride));
}
_MTL_INLINE MTL::StructType* MTL::ArrayType::elementStructType()
{
return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(elementStructType));
}
_MTL_INLINE MTL::ArrayType* MTL::ArrayType::elementArrayType()
{
return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(elementArrayType));
}
_MTL_INLINE MTL::TextureReferenceType* MTL::ArrayType::elementTextureReferenceType()
{
return Object::sendMessage<MTL::TextureReferenceType*>(this, _MTL_PRIVATE_SEL(elementTextureReferenceType));
}
_MTL_INLINE MTL::PointerType* MTL::ArrayType::elementPointerType()
{
return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(elementPointerType));
}
_MTL_INLINE MTL::PointerType* MTL::PointerType::alloc()
{
return NS::Object::alloc<MTL::PointerType>(_MTL_PRIVATE_CLS(MTLPointerType));
}
_MTL_INLINE MTL::PointerType* MTL::PointerType::init()
{
return NS::Object::init<MTL::PointerType>();
}
_MTL_INLINE MTL::DataType MTL::PointerType::elementType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(elementType));
}
_MTL_INLINE MTL::ArgumentAccess MTL::PointerType::access() const
{
return Object::sendMessage<MTL::ArgumentAccess>(this, _MTL_PRIVATE_SEL(access));
}
_MTL_INLINE NS::UInteger MTL::PointerType::alignment() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(alignment));
}
_MTL_INLINE NS::UInteger MTL::PointerType::dataSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(dataSize));
}
_MTL_INLINE bool MTL::PointerType::elementIsArgumentBuffer() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(elementIsArgumentBuffer));
}
_MTL_INLINE MTL::StructType* MTL::PointerType::elementStructType()
{
return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(elementStructType));
}
_MTL_INLINE MTL::ArrayType* MTL::PointerType::elementArrayType()
{
return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(elementArrayType));
}
_MTL_INLINE MTL::TextureReferenceType* MTL::TextureReferenceType::alloc()
{
return NS::Object::alloc<MTL::TextureReferenceType>(_MTL_PRIVATE_CLS(MTLTextureReferenceType));
}
_MTL_INLINE MTL::TextureReferenceType* MTL::TextureReferenceType::init()
{
return NS::Object::init<MTL::TextureReferenceType>();
}
_MTL_INLINE MTL::DataType MTL::TextureReferenceType::textureDataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(textureDataType));
}
_MTL_INLINE MTL::TextureType MTL::TextureReferenceType::textureType() const
{
return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType));
}
_MTL_INLINE MTL::ArgumentAccess MTL::TextureReferenceType::access() const
{
return Object::sendMessage<MTL::ArgumentAccess>(this, _MTL_PRIVATE_SEL(access));
}
_MTL_INLINE bool MTL::TextureReferenceType::isDepthTexture() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthTexture));
}
_MTL_INLINE MTL::Argument* MTL::Argument::alloc()
{
return NS::Object::alloc<MTL::Argument>(_MTL_PRIVATE_CLS(MTLArgument));
}
_MTL_INLINE MTL::Argument* MTL::Argument::init()
{
return NS::Object::init<MTL::Argument>();
}
_MTL_INLINE NS::String* MTL::Argument::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE MTL::ArgumentType MTL::Argument::type() const
{
return Object::sendMessage<MTL::ArgumentType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE MTL::ArgumentAccess MTL::Argument::access() const
{
return Object::sendMessage<MTL::ArgumentAccess>(this, _MTL_PRIVATE_SEL(access));
}
_MTL_INLINE NS::UInteger MTL::Argument::index() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index));
}
_MTL_INLINE bool MTL::Argument::active() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive));
}
_MTL_INLINE NS::UInteger MTL::Argument::bufferAlignment() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferAlignment));
}
_MTL_INLINE NS::UInteger MTL::Argument::bufferDataSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferDataSize));
}
_MTL_INLINE MTL::DataType MTL::Argument::bufferDataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(bufferDataType));
}
_MTL_INLINE MTL::StructType* MTL::Argument::bufferStructType() const
{
return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(bufferStructType));
}
_MTL_INLINE MTL::PointerType* MTL::Argument::bufferPointerType() const
{
return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(bufferPointerType));
}
_MTL_INLINE NS::UInteger MTL::Argument::threadgroupMemoryAlignment() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryAlignment));
}
_MTL_INLINE NS::UInteger MTL::Argument::threadgroupMemoryDataSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryDataSize));
}
_MTL_INLINE MTL::TextureType MTL::Argument::textureType() const
{
return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType));
}
_MTL_INLINE MTL::DataType MTL::Argument::textureDataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(textureDataType));
}
_MTL_INLINE bool MTL::Argument::isDepthTexture() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthTexture));
}
_MTL_INLINE NS::UInteger MTL::Argument::arrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength));
}
#pragma once
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, ResourceUsage) {
ResourceUsageRead = 1,
ResourceUsageWrite = 2,
ResourceUsageSample = 4,
};
_MTL_OPTIONS(NS::UInteger, BarrierScope) {
BarrierScopeBuffers = 1,
BarrierScopeTextures = 2,
BarrierScopeRenderTargets = 4,
};
class CommandEncoder : public NS::Referencing<CommandEncoder>
{
public:
class Device* device() const;
NS::String* label() const;
void setLabel(const NS::String* label);
void endEncoding();
void insertDebugSignpost(const NS::String* string);
void pushDebugGroup(const NS::String* string);
void popDebugGroup();
};
}
_MTL_INLINE MTL::Device* MTL::CommandEncoder::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::CommandEncoder::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::CommandEncoder::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE void MTL::CommandEncoder::endEncoding()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(endEncoding));
}
_MTL_INLINE void MTL::CommandEncoder::insertDebugSignpost(const NS::String* string)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(insertDebugSignpost_), string);
}
_MTL_INLINE void MTL::CommandEncoder::pushDebugGroup(const NS::String* string)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(pushDebugGroup_), string);
}
_MTL_INLINE void MTL::CommandEncoder::popDebugGroup()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(popDebugGroup));
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::Integer, HeapType) {
HeapTypeAutomatic = 0,
HeapTypePlacement = 1,
HeapTypeSparse = 2,
};
class HeapDescriptor : public NS::Copying<HeapDescriptor>
{
public:
static class HeapDescriptor* alloc();
class HeapDescriptor* init();
NS::UInteger size() const;
void setSize(NS::UInteger size);
MTL::StorageMode storageMode() const;
void setStorageMode(MTL::StorageMode storageMode);
MTL::CPUCacheMode cpuCacheMode() const;
void setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode);
MTL::HazardTrackingMode hazardTrackingMode() const;
void setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode);
MTL::ResourceOptions resourceOptions() const;
void setResourceOptions(MTL::ResourceOptions resourceOptions);
MTL::HeapType type() const;
void setType(MTL::HeapType type);
};
class Heap : public NS::Referencing<Heap>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
MTL::StorageMode storageMode() const;
MTL::CPUCacheMode cpuCacheMode() const;
MTL::HazardTrackingMode hazardTrackingMode() const;
MTL::ResourceOptions resourceOptions() const;
NS::UInteger size() const;
NS::UInteger usedSize() const;
NS::UInteger currentAllocatedSize() const;
NS::UInteger maxAvailableSize(NS::UInteger alignment);
class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options);
class Texture* newTexture(const class TextureDescriptor* desc);
MTL::PurgeableState setPurgeableState(MTL::PurgeableState state);
MTL::HeapType type() const;
class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options, NS::UInteger offset);
class Texture* newTexture(const class TextureDescriptor* descriptor, NS::UInteger offset);
};
}
_MTL_INLINE MTL::HeapDescriptor* MTL::HeapDescriptor::alloc()
{
return NS::Object::alloc<MTL::HeapDescriptor>(_MTL_PRIVATE_CLS(MTLHeapDescriptor));
}
_MTL_INLINE MTL::HeapDescriptor* MTL::HeapDescriptor::init()
{
return NS::Object::init<MTL::HeapDescriptor>();
}
_MTL_INLINE NS::UInteger MTL::HeapDescriptor::size() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size));
}
_MTL_INLINE void MTL::HeapDescriptor::setSize(NS::UInteger size)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSize_), size);
}
_MTL_INLINE MTL::StorageMode MTL::HeapDescriptor::storageMode() const
{
return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode));
}
_MTL_INLINE void MTL::HeapDescriptor::setStorageMode(MTL::StorageMode storageMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode);
}
_MTL_INLINE MTL::CPUCacheMode MTL::HeapDescriptor::cpuCacheMode() const
{
return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode));
}
_MTL_INLINE void MTL::HeapDescriptor::setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCpuCacheMode_), cpuCacheMode);
}
_MTL_INLINE MTL::HazardTrackingMode MTL::HeapDescriptor::hazardTrackingMode() const
{
return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode));
}
_MTL_INLINE void MTL::HeapDescriptor::setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHazardTrackingMode_), hazardTrackingMode);
}
_MTL_INLINE MTL::ResourceOptions MTL::HeapDescriptor::resourceOptions() const
{
return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions));
}
_MTL_INLINE void MTL::HeapDescriptor::setResourceOptions(MTL::ResourceOptions resourceOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResourceOptions_), resourceOptions);
}
_MTL_INLINE MTL::HeapType MTL::HeapDescriptor::type() const
{
return Object::sendMessage<MTL::HeapType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE void MTL::HeapDescriptor::setType(MTL::HeapType type)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setType_), type);
}
_MTL_INLINE NS::String* MTL::Heap::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Heap::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::Heap::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::StorageMode MTL::Heap::storageMode() const
{
return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode));
}
_MTL_INLINE MTL::CPUCacheMode MTL::Heap::cpuCacheMode() const
{
return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode));
}
_MTL_INLINE MTL::HazardTrackingMode MTL::Heap::hazardTrackingMode() const
{
return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode));
}
_MTL_INLINE MTL::ResourceOptions MTL::Heap::resourceOptions() const
{
return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions));
}
_MTL_INLINE NS::UInteger MTL::Heap::size() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size));
}
_MTL_INLINE NS::UInteger MTL::Heap::usedSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(usedSize));
}
_MTL_INLINE NS::UInteger MTL::Heap::currentAllocatedSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(currentAllocatedSize));
}
_MTL_INLINE NS::UInteger MTL::Heap::maxAvailableSize(NS::UInteger alignment)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxAvailableSizeWithAlignment_), alignment);
}
_MTL_INLINE MTL::Buffer* MTL::Heap::newBuffer(NS::UInteger length, MTL::ResourceOptions options)
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_), length, options);
}
_MTL_INLINE MTL::Texture* MTL::Heap::newTexture(const MTL::TextureDescriptor* desc)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_), desc);
}
_MTL_INLINE MTL::PurgeableState MTL::Heap::setPurgeableState(MTL::PurgeableState state)
{
return Object::sendMessage<MTL::PurgeableState>(this, _MTL_PRIVATE_SEL(setPurgeableState_), state);
}
_MTL_INLINE MTL::HeapType MTL::Heap::type() const
{
return Object::sendMessage<MTL::HeapType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE MTL::Buffer* MTL::Heap::newBuffer(NS::UInteger length, MTL::ResourceOptions options, NS::UInteger offset)
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_offset_), length, options, offset);
}
_MTL_INLINE MTL::Texture* MTL::Heap::newTexture(const MTL::TextureDescriptor* descriptor, NS::UInteger offset)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_offset_), descriptor, offset);
}
namespace MTL
{
class AccelerationStructureCommandEncoder : public NS::Referencing<AccelerationStructureCommandEncoder, CommandEncoder>
{
public:
void buildAccelerationStructure(const class AccelerationStructure* accelerationStructure, const class AccelerationStructureDescriptor* descriptor, const class Buffer* scratchBuffer, NS::UInteger scratchBufferOffset);
void refitAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructureDescriptor* descriptor, const class AccelerationStructure* destinationAccelerationStructure, const class Buffer* scratchBuffer, NS::UInteger scratchBufferOffset);
void copyAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructure* destinationAccelerationStructure);
void writeCompactedAccelerationStructureSize(const class AccelerationStructure* accelerationStructure, const class Buffer* buffer, NS::UInteger offset);
void writeCompactedAccelerationStructureSize(const class AccelerationStructure* accelerationStructure, const class Buffer* buffer, NS::UInteger offset, MTL::DataType sizeDataType);
void copyAndCompactAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructure* destinationAccelerationStructure);
void updateFence(const class Fence* fence);
void waitForFence(const class Fence* fence);
void useResource(const class Resource* resource, MTL::ResourceUsage usage);
void useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage);
void useHeap(const class Heap* heap);
void useHeaps(MTL::Heap* heaps[], NS::UInteger count);
void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier);
};
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::buildAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, const MTL::AccelerationStructureDescriptor* descriptor, const MTL::Buffer* scratchBuffer, NS::UInteger scratchBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(buildAccelerationStructure_descriptor_scratchBuffer_scratchBufferOffset_), accelerationStructure, descriptor, scratchBuffer, scratchBufferOffset);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::refitAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructureDescriptor* descriptor, const MTL::AccelerationStructure* destinationAccelerationStructure, const MTL::Buffer* scratchBuffer, NS::UInteger scratchBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_), sourceAccelerationStructure, descriptor, destinationAccelerationStructure, scratchBuffer, scratchBufferOffset);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::copyAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructure* destinationAccelerationStructure)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyAccelerationStructure_toAccelerationStructure_), sourceAccelerationStructure, destinationAccelerationStructure);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::writeCompactedAccelerationStructureSize(const MTL::AccelerationStructure* accelerationStructure, const MTL::Buffer* buffer, NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_), accelerationStructure, buffer, offset);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::writeCompactedAccelerationStructureSize(const MTL::AccelerationStructure* accelerationStructure, const MTL::Buffer* buffer, NS::UInteger offset, MTL::DataType sizeDataType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_sizeDataType_), accelerationStructure, buffer, offset, sizeDataType);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::copyAndCompactAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructure* destinationAccelerationStructure)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyAndCompactAccelerationStructure_toAccelerationStructure_), sourceAccelerationStructure, destinationAccelerationStructure);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::updateFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::waitForFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useHeap(const MTL::Heap* heap)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useHeaps(MTL::Heap* heaps[], NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count);
}
_MTL_INLINE void MTL::AccelerationStructureCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier);
}
#pragma once
#pragma once
namespace MTL
{
class Buffer : public NS::Referencing<Buffer, Resource>
{
public:
NS::UInteger length() const;
void* contents();
void didModifyRange(NS::Range range);
class Texture* newTexture(const class TextureDescriptor* descriptor, NS::UInteger offset, NS::UInteger bytesPerRow);
void addDebugMarker(const NS::String* marker, NS::Range range);
void removeAllDebugMarkers();
class Buffer* remoteStorageBuffer() const;
class Buffer* newRemoteBufferViewForDevice(const class Device* device);
};
}
_MTL_INLINE NS::UInteger MTL::Buffer::length() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(length));
}
_MTL_INLINE void* MTL::Buffer::contents()
{
return Object::sendMessage<void*>(this, _MTL_PRIVATE_SEL(contents));
}
_MTL_INLINE void MTL::Buffer::didModifyRange(NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(didModifyRange_), range);
}
_MTL_INLINE MTL::Texture* MTL::Buffer::newTexture(const MTL::TextureDescriptor* descriptor, NS::UInteger offset, NS::UInteger bytesPerRow)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_offset_bytesPerRow_), descriptor, offset, bytesPerRow);
}
_MTL_INLINE void MTL::Buffer::addDebugMarker(const NS::String* marker, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addDebugMarker_range_), marker, range);
}
_MTL_INLINE void MTL::Buffer::removeAllDebugMarkers()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(removeAllDebugMarkers));
}
_MTL_INLINE MTL::Buffer* MTL::Buffer::remoteStorageBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(remoteStorageBuffer));
}
_MTL_INLINE MTL::Buffer* MTL::Buffer::newRemoteBufferViewForDevice(const MTL::Device* device)
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newRemoteBufferViewForDevice_), device);
}
#pragma once
namespace MTL
{
class ComputePipelineReflection : public NS::Referencing<ComputePipelineReflection>
{
public:
static class ComputePipelineReflection* alloc();
class ComputePipelineReflection* init();
NS::Array* arguments() const;
};
class ComputePipelineDescriptor : public NS::Copying<ComputePipelineDescriptor>
{
public:
static class ComputePipelineDescriptor* alloc();
class ComputePipelineDescriptor* init();
NS::String* label() const;
void setLabel(const NS::String* label);
class Function* computeFunction() const;
void setComputeFunction(const class Function* computeFunction);
bool threadGroupSizeIsMultipleOfThreadExecutionWidth() const;
void setThreadGroupSizeIsMultipleOfThreadExecutionWidth(bool threadGroupSizeIsMultipleOfThreadExecutionWidth);
NS::UInteger maxTotalThreadsPerThreadgroup() const;
void setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup);
class StageInputOutputDescriptor* stageInputDescriptor() const;
void setStageInputDescriptor(const class StageInputOutputDescriptor* stageInputDescriptor);
class PipelineBufferDescriptorArray* buffers() const;
bool supportIndirectCommandBuffers() const;
void setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers);
NS::Array* insertLibraries() const;
void setInsertLibraries(const NS::Array* insertLibraries);
NS::Array* preloadedLibraries() const;
void setPreloadedLibraries(const NS::Array* preloadedLibraries);
NS::Array* binaryArchives() const;
void setBinaryArchives(const NS::Array* binaryArchives);
void reset();
class LinkedFunctions* linkedFunctions() const;
void setLinkedFunctions(const class LinkedFunctions* linkedFunctions);
bool supportAddingBinaryFunctions() const;
void setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions);
NS::UInteger maxCallStackDepth() const;
void setMaxCallStackDepth(NS::UInteger maxCallStackDepth);
};
class ComputePipelineState : public NS::Referencing<ComputePipelineState>
{
public:
NS::String* label() const;
class Device* device() const;
NS::UInteger maxTotalThreadsPerThreadgroup() const;
NS::UInteger threadExecutionWidth() const;
NS::UInteger staticThreadgroupMemoryLength() const;
NS::UInteger imageblockMemoryLength(MTL::Size imageblockDimensions);
bool supportIndirectCommandBuffers() const;
class FunctionHandle* functionHandle(const class Function* function);
class ComputePipelineState* newComputePipelineState(const NS::Array* functions, NS::Error** error);
class VisibleFunctionTable* newVisibleFunctionTable(const class VisibleFunctionTableDescriptor* descriptor);
class IntersectionFunctionTable* newIntersectionFunctionTable(const class IntersectionFunctionTableDescriptor* descriptor);
};
}
_MTL_INLINE MTL::ComputePipelineReflection* MTL::ComputePipelineReflection::alloc()
{
return NS::Object::alloc<MTL::ComputePipelineReflection>(_MTL_PRIVATE_CLS(MTLComputePipelineReflection));
}
_MTL_INLINE MTL::ComputePipelineReflection* MTL::ComputePipelineReflection::init()
{
return NS::Object::init<MTL::ComputePipelineReflection>();
}
_MTL_INLINE NS::Array* MTL::ComputePipelineReflection::arguments() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(arguments));
}
_MTL_INLINE MTL::ComputePipelineDescriptor* MTL::ComputePipelineDescriptor::alloc()
{
return NS::Object::alloc<MTL::ComputePipelineDescriptor>(_MTL_PRIVATE_CLS(MTLComputePipelineDescriptor));
}
_MTL_INLINE MTL::ComputePipelineDescriptor* MTL::ComputePipelineDescriptor::init()
{
return NS::Object::init<MTL::ComputePipelineDescriptor>();
}
_MTL_INLINE NS::String* MTL::ComputePipelineDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Function* MTL::ComputePipelineDescriptor::computeFunction() const
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(computeFunction));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setComputeFunction(const MTL::Function* computeFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputeFunction_), computeFunction);
}
_MTL_INLINE bool MTL::ComputePipelineDescriptor::threadGroupSizeIsMultipleOfThreadExecutionWidth() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadGroupSizeIsMultipleOfThreadExecutionWidth));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setThreadGroupSizeIsMultipleOfThreadExecutionWidth(bool threadGroupSizeIsMultipleOfThreadExecutionWidth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadGroupSizeIsMultipleOfThreadExecutionWidth_), threadGroupSizeIsMultipleOfThreadExecutionWidth);
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineDescriptor::maxTotalThreadsPerThreadgroup() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerThreadgroup_), maxTotalThreadsPerThreadgroup);
}
_MTL_INLINE MTL::StageInputOutputDescriptor* MTL::ComputePipelineDescriptor::stageInputDescriptor() const
{
return Object::sendMessage<MTL::StageInputOutputDescriptor*>(this, _MTL_PRIVATE_SEL(stageInputDescriptor));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setStageInputDescriptor(const MTL::StageInputOutputDescriptor* stageInputDescriptor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInputDescriptor_), stageInputDescriptor);
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::ComputePipelineDescriptor::buffers() const
{
return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(buffers));
}
_MTL_INLINE bool MTL::ComputePipelineDescriptor::supportIndirectCommandBuffers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportIndirectCommandBuffers_), supportIndirectCommandBuffers);
}
_MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::insertLibraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(insertLibraries));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setInsertLibraries(const NS::Array* insertLibraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInsertLibraries_), insertLibraries);
}
_MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::preloadedLibraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(preloadedLibraries));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setPreloadedLibraries(const NS::Array* preloadedLibraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreloadedLibraries_), preloadedLibraries);
}
_MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::binaryArchives() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives);
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
_MTL_INLINE MTL::LinkedFunctions* MTL::ComputePipelineDescriptor::linkedFunctions() const
{
return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(linkedFunctions));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setLinkedFunctions(const MTL::LinkedFunctions* linkedFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLinkedFunctions_), linkedFunctions);
}
_MTL_INLINE bool MTL::ComputePipelineDescriptor::supportAddingBinaryFunctions() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingBinaryFunctions));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingBinaryFunctions_), supportAddingBinaryFunctions);
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineDescriptor::maxCallStackDepth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCallStackDepth));
}
_MTL_INLINE void MTL::ComputePipelineDescriptor::setMaxCallStackDepth(NS::UInteger maxCallStackDepth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCallStackDepth_), maxCallStackDepth);
}
_MTL_INLINE NS::String* MTL::ComputePipelineState::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::Device* MTL::ComputePipelineState::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineState::maxTotalThreadsPerThreadgroup() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup));
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineState::threadExecutionWidth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadExecutionWidth));
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineState::staticThreadgroupMemoryLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(staticThreadgroupMemoryLength));
}
_MTL_INLINE NS::UInteger MTL::ComputePipelineState::imageblockMemoryLength(MTL::Size imageblockDimensions)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockMemoryLengthForDimensions_), imageblockDimensions);
}
_MTL_INLINE bool MTL::ComputePipelineState::supportIndirectCommandBuffers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers));
}
_MTL_INLINE MTL::FunctionHandle* MTL::ComputePipelineState::functionHandle(const MTL::Function* function)
{
return Object::sendMessage<MTL::FunctionHandle*>(this, _MTL_PRIVATE_SEL(functionHandleWithFunction_), function);
}
_MTL_INLINE MTL::ComputePipelineState* MTL::ComputePipelineState::newComputePipelineState(const NS::Array* functions, NS::Error** error)
{
return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithAdditionalBinaryFunctions_error_), functions, error);
}
_MTL_INLINE MTL::VisibleFunctionTable* MTL::ComputePipelineState::newVisibleFunctionTable(const MTL::VisibleFunctionTableDescriptor* descriptor)
{
return Object::sendMessage<MTL::VisibleFunctionTable*>(this, _MTL_PRIVATE_SEL(newVisibleFunctionTableWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::IntersectionFunctionTable* MTL::ComputePipelineState::newIntersectionFunctionTable(const MTL::IntersectionFunctionTableDescriptor* descriptor)
{
return Object::sendMessage<MTL::IntersectionFunctionTable*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionTableWithDescriptor_), descriptor);
}
#pragma once
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, IndirectCommandType) {
IndirectCommandTypeDraw = 1,
IndirectCommandTypeDrawIndexed = 2,
IndirectCommandTypeDrawPatches = 4,
IndirectCommandTypeDrawIndexedPatches = 8,
IndirectCommandTypeConcurrentDispatch = 32,
IndirectCommandTypeConcurrentDispatchThreads = 64,
};
struct IndirectCommandBufferExecutionRange
{
uint32_t location;
uint32_t length;
} _MTL_PACKED;
class IndirectCommandBufferDescriptor : public NS::Copying<IndirectCommandBufferDescriptor>
{
public:
static class IndirectCommandBufferDescriptor* alloc();
class IndirectCommandBufferDescriptor* init();
MTL::IndirectCommandType commandTypes() const;
void setCommandTypes(MTL::IndirectCommandType commandTypes);
bool inheritPipelineState() const;
void setInheritPipelineState(bool inheritPipelineState);
bool inheritBuffers() const;
void setInheritBuffers(bool inheritBuffers);
NS::UInteger maxVertexBufferBindCount() const;
void setMaxVertexBufferBindCount(NS::UInteger maxVertexBufferBindCount);
NS::UInteger maxFragmentBufferBindCount() const;
void setMaxFragmentBufferBindCount(NS::UInteger maxFragmentBufferBindCount);
NS::UInteger maxKernelBufferBindCount() const;
void setMaxKernelBufferBindCount(NS::UInteger maxKernelBufferBindCount);
};
class IndirectCommandBuffer : public NS::Referencing<IndirectCommandBuffer, Resource>
{
public:
NS::UInteger size() const;
void reset(NS::Range range);
class IndirectRenderCommand* indirectRenderCommand(NS::UInteger commandIndex);
class IndirectComputeCommand* indirectComputeCommand(NS::UInteger commandIndex);
};
}
_MTL_INLINE MTL::IndirectCommandBufferDescriptor* MTL::IndirectCommandBufferDescriptor::alloc()
{
return NS::Object::alloc<MTL::IndirectCommandBufferDescriptor>(_MTL_PRIVATE_CLS(MTLIndirectCommandBufferDescriptor));
}
_MTL_INLINE MTL::IndirectCommandBufferDescriptor* MTL::IndirectCommandBufferDescriptor::init()
{
return NS::Object::init<MTL::IndirectCommandBufferDescriptor>();
}
_MTL_INLINE MTL::IndirectCommandType MTL::IndirectCommandBufferDescriptor::commandTypes() const
{
return Object::sendMessage<MTL::IndirectCommandType>(this, _MTL_PRIVATE_SEL(commandTypes));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setCommandTypes(MTL::IndirectCommandType commandTypes)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCommandTypes_), commandTypes);
}
_MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::inheritPipelineState() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(inheritPipelineState));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setInheritPipelineState(bool inheritPipelineState)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInheritPipelineState_), inheritPipelineState);
}
_MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::inheritBuffers() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(inheritBuffers));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setInheritBuffers(bool inheritBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInheritBuffers_), inheritBuffers);
}
_MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxVertexBufferBindCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexBufferBindCount));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxVertexBufferBindCount(NS::UInteger maxVertexBufferBindCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexBufferBindCount_), maxVertexBufferBindCount);
}
_MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxFragmentBufferBindCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxFragmentBufferBindCount));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxFragmentBufferBindCount(NS::UInteger maxFragmentBufferBindCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxFragmentBufferBindCount_), maxFragmentBufferBindCount);
}
_MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxKernelBufferBindCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxKernelBufferBindCount));
}
_MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxKernelBufferBindCount(NS::UInteger maxKernelBufferBindCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxKernelBufferBindCount_), maxKernelBufferBindCount);
}
_MTL_INLINE NS::UInteger MTL::IndirectCommandBuffer::size() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size));
}
_MTL_INLINE void MTL::IndirectCommandBuffer::reset(NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetWithRange_), range);
}
_MTL_INLINE MTL::IndirectRenderCommand* MTL::IndirectCommandBuffer::indirectRenderCommand(NS::UInteger commandIndex)
{
return Object::sendMessage<MTL::IndirectRenderCommand*>(this, _MTL_PRIVATE_SEL(indirectRenderCommandAtIndex_), commandIndex);
}
_MTL_INLINE MTL::IndirectComputeCommand* MTL::IndirectCommandBuffer::indirectComputeCommand(NS::UInteger commandIndex)
{
return Object::sendMessage<MTL::IndirectComputeCommand*>(this, _MTL_PRIVATE_SEL(indirectComputeCommandAtIndex_), commandIndex);
}
#pragma once
#pragma once
#pragma once
#pragma once
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, FunctionOptions) {
FunctionOptionNone = 0,
FunctionOptionCompileToBinary = 1,
};
class FunctionDescriptor : public NS::Copying<FunctionDescriptor>
{
public:
static class FunctionDescriptor* alloc();
class FunctionDescriptor* init();
static class FunctionDescriptor* functionDescriptor();
NS::String* name() const;
void setName(const NS::String* name);
NS::String* specializedName() const;
void setSpecializedName(const NS::String* specializedName);
class FunctionConstantValues* constantValues() const;
void setConstantValues(const class FunctionConstantValues* constantValues);
MTL::FunctionOptions options() const;
void setOptions(MTL::FunctionOptions options);
NS::Array* binaryArchives() const;
void setBinaryArchives(const NS::Array* binaryArchives);
};
class IntersectionFunctionDescriptor : public NS::Copying<IntersectionFunctionDescriptor, MTL::FunctionDescriptor>
{
public:
static class IntersectionFunctionDescriptor* alloc();
class IntersectionFunctionDescriptor* init();
};
}
_MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::alloc()
{
return NS::Object::alloc<MTL::FunctionDescriptor>(_MTL_PRIVATE_CLS(MTLFunctionDescriptor));
}
_MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::init()
{
return NS::Object::init<MTL::FunctionDescriptor>();
}
_MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::functionDescriptor()
{
return Object::sendMessage<MTL::FunctionDescriptor*>(_MTL_PRIVATE_CLS(MTLFunctionDescriptor), _MTL_PRIVATE_SEL(functionDescriptor));
}
_MTL_INLINE NS::String* MTL::FunctionDescriptor::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE void MTL::FunctionDescriptor::setName(const NS::String* name)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setName_), name);
}
_MTL_INLINE NS::String* MTL::FunctionDescriptor::specializedName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(specializedName));
}
_MTL_INLINE void MTL::FunctionDescriptor::setSpecializedName(const NS::String* specializedName)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSpecializedName_), specializedName);
}
_MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionDescriptor::constantValues() const
{
return Object::sendMessage<MTL::FunctionConstantValues*>(this, _MTL_PRIVATE_SEL(constantValues));
}
_MTL_INLINE void MTL::FunctionDescriptor::setConstantValues(const MTL::FunctionConstantValues* constantValues)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValues_), constantValues);
}
_MTL_INLINE MTL::FunctionOptions MTL::FunctionDescriptor::options() const
{
return Object::sendMessage<MTL::FunctionOptions>(this, _MTL_PRIVATE_SEL(options));
}
_MTL_INLINE void MTL::FunctionDescriptor::setOptions(MTL::FunctionOptions options)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOptions_), options);
}
_MTL_INLINE NS::Array* MTL::FunctionDescriptor::binaryArchives() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives));
}
_MTL_INLINE void MTL::FunctionDescriptor::setBinaryArchives(const NS::Array* binaryArchives)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives);
}
_MTL_INLINE MTL::IntersectionFunctionDescriptor* MTL::IntersectionFunctionDescriptor::alloc()
{
return NS::Object::alloc<MTL::IntersectionFunctionDescriptor>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionDescriptor));
}
_MTL_INLINE MTL::IntersectionFunctionDescriptor* MTL::IntersectionFunctionDescriptor::init()
{
return NS::Object::init<MTL::IntersectionFunctionDescriptor>();
}
#include <functional>
namespace MTL
{
_MTL_ENUM(NS::UInteger, PatchType) {
PatchTypeNone = 0,
PatchTypeTriangle = 1,
PatchTypeQuad = 2,
};
class VertexAttribute : public NS::Referencing<VertexAttribute>
{
public:
static class VertexAttribute* alloc();
class VertexAttribute* init();
NS::String* name() const;
NS::UInteger attributeIndex() const;
MTL::DataType attributeType() const;
bool active() const;
bool patchData() const;
bool patchControlPointData() const;
};
class Attribute : public NS::Referencing<Attribute>
{
public:
static class Attribute* alloc();
class Attribute* init();
NS::String* name() const;
NS::UInteger attributeIndex() const;
MTL::DataType attributeType() const;
bool active() const;
bool patchData() const;
bool patchControlPointData() const;
};
_MTL_ENUM(NS::UInteger, FunctionType) {
FunctionTypeVertex = 1,
FunctionTypeFragment = 2,
FunctionTypeKernel = 3,
FunctionTypeVisible = 5,
FunctionTypeIntersection = 6,
};
class FunctionConstant : public NS::Referencing<FunctionConstant>
{
public:
static class FunctionConstant* alloc();
class FunctionConstant* init();
NS::String* name() const;
MTL::DataType type() const;
NS::UInteger index() const;
bool required() const;
};
using AutoreleasedArgument = class Argument*;
class Function : public NS::Referencing<Function>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
MTL::FunctionType functionType() const;
MTL::PatchType patchType() const;
NS::Integer patchControlPointCount() const;
NS::Array* vertexAttributes() const;
NS::Array* stageInputAttributes() const;
NS::String* name() const;
NS::Dictionary* functionConstantsDictionary() const;
class ArgumentEncoder* newArgumentEncoder(NS::UInteger bufferIndex);
class ArgumentEncoder* newArgumentEncoder(NS::UInteger bufferIndex, const MTL::AutoreleasedArgument* reflection);
MTL::FunctionOptions options() const;
};
_MTL_ENUM(NS::UInteger, LanguageVersion) {
LanguageVersion1_0 = 65536,
LanguageVersion1_1 = 65537,
LanguageVersion1_2 = 65538,
LanguageVersion2_0 = 131072,
LanguageVersion2_1 = 131073,
LanguageVersion2_2 = 131074,
LanguageVersion2_3 = 131075,
LanguageVersion2_4 = 131076,
};
_MTL_ENUM(NS::Integer, LibraryType) {
LibraryTypeExecutable = 0,
LibraryTypeDynamic = 1,
};
class CompileOptions : public NS::Copying<CompileOptions>
{
public:
static class CompileOptions* alloc();
class CompileOptions* init();
NS::Dictionary* preprocessorMacros() const;
void setPreprocessorMacros(const NS::Dictionary* preprocessorMacros);
bool fastMathEnabled() const;
void setFastMathEnabled(bool fastMathEnabled);
MTL::LanguageVersion languageVersion() const;
void setLanguageVersion(MTL::LanguageVersion languageVersion);
MTL::LibraryType libraryType() const;
void setLibraryType(MTL::LibraryType libraryType);
NS::String* installName() const;
void setInstallName(const NS::String* installName);
NS::Array* libraries() const;
void setLibraries(const NS::Array* libraries);
bool preserveInvariance() const;
void setPreserveInvariance(bool preserveInvariance);
};
_MTL_ENUM(NS::UInteger, LibraryError) {
LibraryErrorUnsupported = 1,
LibraryErrorCompileFailure = 3,
LibraryErrorCompileWarning = 4,
LibraryErrorFunctionNotFound = 5,
LibraryErrorFileNotFound = 6,
};
class Library : public NS::Referencing<Library>
{
public:
void newFunction(const NS::String* pFunctionName, const class FunctionConstantValues* pConstantValues, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler);
void newFunction(const class FunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler);
void newIntersectionFunction(const class IntersectionFunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler);
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
class Function* newFunction(const NS::String* functionName);
class Function* newFunction(const NS::String* name, const class FunctionConstantValues* constantValues, NS::Error** error);
void newFunction(const NS::String* name, const class FunctionConstantValues* constantValues, void (^completionHandler)(MTL::Function*, NS::Error*));
void newFunction(const class FunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*));
class Function* newFunction(const class FunctionDescriptor* descriptor, NS::Error** error);
void newIntersectionFunction(const class IntersectionFunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*));
class Function* newIntersectionFunction(const class IntersectionFunctionDescriptor* descriptor, NS::Error** error);
NS::Array* functionNames() const;
MTL::LibraryType type() const;
NS::String* installName() const;
};
}
_MTL_INLINE MTL::VertexAttribute* MTL::VertexAttribute::alloc()
{
return NS::Object::alloc<MTL::VertexAttribute>(_MTL_PRIVATE_CLS(MTLVertexAttribute));
}
_MTL_INLINE MTL::VertexAttribute* MTL::VertexAttribute::init()
{
return NS::Object::init<MTL::VertexAttribute>();
}
_MTL_INLINE NS::String* MTL::VertexAttribute::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::UInteger MTL::VertexAttribute::attributeIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(attributeIndex));
}
_MTL_INLINE MTL::DataType MTL::VertexAttribute::attributeType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(attributeType));
}
_MTL_INLINE bool MTL::VertexAttribute::active() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive));
}
_MTL_INLINE bool MTL::VertexAttribute::patchData() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchData));
}
_MTL_INLINE bool MTL::VertexAttribute::patchControlPointData() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchControlPointData));
}
_MTL_INLINE MTL::Attribute* MTL::Attribute::alloc()
{
return NS::Object::alloc<MTL::Attribute>(_MTL_PRIVATE_CLS(MTLAttribute));
}
_MTL_INLINE MTL::Attribute* MTL::Attribute::init()
{
return NS::Object::init<MTL::Attribute>();
}
_MTL_INLINE NS::String* MTL::Attribute::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::UInteger MTL::Attribute::attributeIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(attributeIndex));
}
_MTL_INLINE MTL::DataType MTL::Attribute::attributeType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(attributeType));
}
_MTL_INLINE bool MTL::Attribute::active() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive));
}
_MTL_INLINE bool MTL::Attribute::patchData() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchData));
}
_MTL_INLINE bool MTL::Attribute::patchControlPointData() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchControlPointData));
}
_MTL_INLINE MTL::FunctionConstant* MTL::FunctionConstant::alloc()
{
return NS::Object::alloc<MTL::FunctionConstant>(_MTL_PRIVATE_CLS(MTLFunctionConstant));
}
_MTL_INLINE MTL::FunctionConstant* MTL::FunctionConstant::init()
{
return NS::Object::init<MTL::FunctionConstant>();
}
_MTL_INLINE NS::String* MTL::FunctionConstant::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE MTL::DataType MTL::FunctionConstant::type() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE NS::UInteger MTL::FunctionConstant::index() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index));
}
_MTL_INLINE bool MTL::FunctionConstant::required() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(required));
}
_MTL_INLINE NS::String* MTL::Function::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Function::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::Function::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::FunctionType MTL::Function::functionType() const
{
return Object::sendMessage<MTL::FunctionType>(this, _MTL_PRIVATE_SEL(functionType));
}
_MTL_INLINE MTL::PatchType MTL::Function::patchType() const
{
return Object::sendMessage<MTL::PatchType>(this, _MTL_PRIVATE_SEL(patchType));
}
_MTL_INLINE NS::Integer MTL::Function::patchControlPointCount() const
{
return Object::sendMessage<NS::Integer>(this, _MTL_PRIVATE_SEL(patchControlPointCount));
}
_MTL_INLINE NS::Array* MTL::Function::vertexAttributes() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexAttributes));
}
_MTL_INLINE NS::Array* MTL::Function::stageInputAttributes() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(stageInputAttributes));
}
_MTL_INLINE NS::String* MTL::Function::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::Dictionary* MTL::Function::functionConstantsDictionary() const
{
return Object::sendMessage<NS::Dictionary*>(this, _MTL_PRIVATE_SEL(functionConstantsDictionary));
}
_MTL_INLINE MTL::ArgumentEncoder* MTL::Function::newArgumentEncoder(NS::UInteger bufferIndex)
{
return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithBufferIndex_), bufferIndex);
}
_MTL_INLINE MTL::ArgumentEncoder* MTL::Function::newArgumentEncoder(NS::UInteger bufferIndex, const MTL::AutoreleasedArgument* reflection)
{
return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithBufferIndex_reflection_), bufferIndex, reflection);
}
_MTL_INLINE MTL::FunctionOptions MTL::Function::options() const
{
return Object::sendMessage<MTL::FunctionOptions>(this, _MTL_PRIVATE_SEL(options));
}
_MTL_INLINE MTL::CompileOptions* MTL::CompileOptions::alloc()
{
return NS::Object::alloc<MTL::CompileOptions>(_MTL_PRIVATE_CLS(MTLCompileOptions));
}
_MTL_INLINE MTL::CompileOptions* MTL::CompileOptions::init()
{
return NS::Object::init<MTL::CompileOptions>();
}
_MTL_INLINE NS::Dictionary* MTL::CompileOptions::preprocessorMacros() const
{
return Object::sendMessage<NS::Dictionary*>(this, _MTL_PRIVATE_SEL(preprocessorMacros));
}
_MTL_INLINE void MTL::CompileOptions::setPreprocessorMacros(const NS::Dictionary* preprocessorMacros)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreprocessorMacros_), preprocessorMacros);
}
_MTL_INLINE bool MTL::CompileOptions::fastMathEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(fastMathEnabled));
}
_MTL_INLINE void MTL::CompileOptions::setFastMathEnabled(bool fastMathEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFastMathEnabled_), fastMathEnabled);
}
_MTL_INLINE MTL::LanguageVersion MTL::CompileOptions::languageVersion() const
{
return Object::sendMessage<MTL::LanguageVersion>(this, _MTL_PRIVATE_SEL(languageVersion));
}
_MTL_INLINE void MTL::CompileOptions::setLanguageVersion(MTL::LanguageVersion languageVersion)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLanguageVersion_), languageVersion);
}
_MTL_INLINE MTL::LibraryType MTL::CompileOptions::libraryType() const
{
return Object::sendMessage<MTL::LibraryType>(this, _MTL_PRIVATE_SEL(libraryType));
}
_MTL_INLINE void MTL::CompileOptions::setLibraryType(MTL::LibraryType libraryType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLibraryType_), libraryType);
}
_MTL_INLINE NS::String* MTL::CompileOptions::installName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName));
}
_MTL_INLINE void MTL::CompileOptions::setInstallName(const NS::String* installName)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstallName_), installName);
}
_MTL_INLINE NS::Array* MTL::CompileOptions::libraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(libraries));
}
_MTL_INLINE void MTL::CompileOptions::setLibraries(const NS::Array* libraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLibraries_), libraries);
}
_MTL_INLINE bool MTL::CompileOptions::preserveInvariance() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(preserveInvariance));
}
_MTL_INLINE void MTL::CompileOptions::setPreserveInvariance(bool preserveInvariance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreserveInvariance_), preserveInvariance);
}
_MTL_INLINE void MTL::Library::newFunction(const NS::String* pFunctionName, const FunctionConstantValues* pConstantValues, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler)
{
__block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler;
newFunction(pFunctionName, pConstantValues, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); });
}
_MTL_INLINE void MTL::Library::newFunction(const FunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler)
{
__block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler;
newFunction(pDescriptor, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); });
}
_MTL_INLINE void MTL::Library::newIntersectionFunction(const IntersectionFunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler)
{
__block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler;
newIntersectionFunction(pDescriptor, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); });
}
_MTL_INLINE NS::String* MTL::Library::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Library::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::Library::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::Function* MTL::Library::newFunction(const NS::String* functionName)
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithName_), functionName);
}
_MTL_INLINE MTL::Function* MTL::Library::newFunction(const NS::String* name, const MTL::FunctionConstantValues* constantValues, NS::Error** error)
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithName_constantValues_error_), name, constantValues, error);
}
_MTL_INLINE void MTL::Library::newFunction(const NS::String* name, const MTL::FunctionConstantValues* constantValues, void (^completionHandler)(MTL::Function*, NS::Error*))
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newFunctionWithName_constantValues_completionHandler_), name, constantValues, completionHandler);
}
_MTL_INLINE void MTL::Library::newFunction(const MTL::FunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*))
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newFunctionWithDescriptor_completionHandler_), descriptor, completionHandler);
}
_MTL_INLINE MTL::Function* MTL::Library::newFunction(const MTL::FunctionDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE void MTL::Library::newIntersectionFunction(const MTL::IntersectionFunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*))
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionWithDescriptor_completionHandler_), descriptor, completionHandler);
}
_MTL_INLINE MTL::Function* MTL::Library::newIntersectionFunction(const MTL::IntersectionFunctionDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE NS::Array* MTL::Library::functionNames() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functionNames));
}
_MTL_INLINE MTL::LibraryType MTL::Library::type() const
{
return Object::sendMessage<MTL::LibraryType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE NS::String* MTL::Library::installName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName));
}
namespace MTL
{
class FunctionHandle : public NS::Referencing<FunctionHandle>
{
public:
MTL::FunctionType functionType() const;
NS::String* name() const;
class Device* device() const;
};
}
_MTL_INLINE MTL::FunctionType MTL::FunctionHandle::functionType() const
{
return Object::sendMessage<MTL::FunctionType>(this, _MTL_PRIVATE_SEL(functionType));
}
_MTL_INLINE NS::String* MTL::FunctionHandle::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE MTL::Device* MTL::FunctionHandle::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
#pragma once
namespace MTL
{
class VisibleFunctionTableDescriptor : public NS::Copying<VisibleFunctionTableDescriptor>
{
public:
static class VisibleFunctionTableDescriptor* alloc();
class VisibleFunctionTableDescriptor* init();
static class VisibleFunctionTableDescriptor* visibleFunctionTableDescriptor();
NS::UInteger functionCount() const;
void setFunctionCount(NS::UInteger functionCount);
};
class VisibleFunctionTable : public NS::Referencing<VisibleFunctionTable, Resource>
{
public:
void setFunction(const class FunctionHandle* function, NS::UInteger index);
void setFunctions(const class FunctionHandle* functions[], NS::Range range);
};
}
_MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::alloc()
{
return NS::Object::alloc<MTL::VisibleFunctionTableDescriptor>(_MTL_PRIVATE_CLS(MTLVisibleFunctionTableDescriptor));
}
_MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::init()
{
return NS::Object::init<MTL::VisibleFunctionTableDescriptor>();
}
_MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::visibleFunctionTableDescriptor()
{
return Object::sendMessage<MTL::VisibleFunctionTableDescriptor*>(_MTL_PRIVATE_CLS(MTLVisibleFunctionTableDescriptor), _MTL_PRIVATE_SEL(visibleFunctionTableDescriptor));
}
_MTL_INLINE NS::UInteger MTL::VisibleFunctionTableDescriptor::functionCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(functionCount));
}
_MTL_INLINE void MTL::VisibleFunctionTableDescriptor::setFunctionCount(NS::UInteger functionCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionCount_), functionCount);
}
_MTL_INLINE void MTL::VisibleFunctionTable::setFunction(const MTL::FunctionHandle* function, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunction_atIndex_), function, index);
}
_MTL_INLINE void MTL::VisibleFunctionTable::setFunctions(const MTL::FunctionHandle* functions[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_withRange_), functions, range);
}
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, IntersectionFunctionSignature) {
IntersectionFunctionSignatureNone = 0,
IntersectionFunctionSignatureInstancing = 1,
IntersectionFunctionSignatureTriangleData = 2,
IntersectionFunctionSignatureWorldSpaceData = 4,
IntersectionFunctionSignatureInstanceMotion = 8,
IntersectionFunctionSignaturePrimitiveMotion = 16,
IntersectionFunctionSignatureExtendedLimits = 32,
};
class IntersectionFunctionTableDescriptor : public NS::Copying<IntersectionFunctionTableDescriptor>
{
public:
static class IntersectionFunctionTableDescriptor* alloc();
class IntersectionFunctionTableDescriptor* init();
static class IntersectionFunctionTableDescriptor* intersectionFunctionTableDescriptor();
NS::UInteger functionCount() const;
void setFunctionCount(NS::UInteger functionCount);
};
class IntersectionFunctionTable : public NS::Referencing<IntersectionFunctionTable, Resource>
{
public:
void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setBuffers(const class Buffer* buffers[], const NS::UInteger offsets[], NS::Range range);
void setFunction(const class FunctionHandle* function, NS::UInteger index);
void setFunctions(const class FunctionHandle* functions[], NS::Range range);
void setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index);
void setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range);
void setVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex);
void setVisibleFunctionTables(const class VisibleFunctionTable* functionTables[], NS::Range bufferRange);
};
}
_MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::alloc()
{
return NS::Object::alloc<MTL::IntersectionFunctionTableDescriptor>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionTableDescriptor));
}
_MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::init()
{
return NS::Object::init<MTL::IntersectionFunctionTableDescriptor>();
}
_MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::intersectionFunctionTableDescriptor()
{
return Object::sendMessage<MTL::IntersectionFunctionTableDescriptor*>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionTableDescriptor), _MTL_PRIVATE_SEL(intersectionFunctionTableDescriptor));
}
_MTL_INLINE NS::UInteger MTL::IntersectionFunctionTableDescriptor::functionCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(functionCount));
}
_MTL_INLINE void MTL::IntersectionFunctionTableDescriptor::setFunctionCount(NS::UInteger functionCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionCount_), functionCount);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setBuffers(const MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setFunction(const MTL::FunctionHandle* function, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunction_atIndex_), function, index);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setFunctions(const MTL::FunctionHandle* functions[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_withRange_), functions, range);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_atIndex_), signature, index);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_withRange_), signature, range);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex);
}
_MTL_INLINE void MTL::IntersectionFunctionTable::setVisibleFunctionTables(const MTL::VisibleFunctionTable* functionTables[], NS::Range bufferRange)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withBufferRange_), functionTables, bufferRange);
}
#pragma once
#pragma once
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, LoadAction) {
LoadActionDontCare = 0,
LoadActionLoad = 1,
LoadActionClear = 2,
};
_MTL_ENUM(NS::UInteger, StoreAction) {
StoreActionDontCare = 0,
StoreActionStore = 1,
StoreActionMultisampleResolve = 2,
StoreActionStoreAndMultisampleResolve = 3,
StoreActionUnknown = 4,
StoreActionCustomSampleDepthStore = 5,
};
_MTL_OPTIONS(NS::UInteger, StoreActionOptions) {
StoreActionOptionNone = 0,
StoreActionOptionValidMask = 1,
StoreActionOptionCustomSamplePositions = 1,
};
struct ClearColor
{
static ClearColor Make(double red, double green, double blue, double alpha);
ClearColor() = default;
ClearColor(double red, double green, double blue, double alpha);
double red;
double green;
double blue;
double alpha;
} _MTL_PACKED;
class RenderPassAttachmentDescriptor : public NS::Copying<RenderPassAttachmentDescriptor>
{
public:
static class RenderPassAttachmentDescriptor* alloc();
class RenderPassAttachmentDescriptor* init();
class Texture* texture() const;
void setTexture(const class Texture* texture);
NS::UInteger level() const;
void setLevel(NS::UInteger level);
NS::UInteger slice() const;
void setSlice(NS::UInteger slice);
NS::UInteger depthPlane() const;
void setDepthPlane(NS::UInteger depthPlane);
class Texture* resolveTexture() const;
void setResolveTexture(const class Texture* resolveTexture);
NS::UInteger resolveLevel() const;
void setResolveLevel(NS::UInteger resolveLevel);
NS::UInteger resolveSlice() const;
void setResolveSlice(NS::UInteger resolveSlice);
NS::UInteger resolveDepthPlane() const;
void setResolveDepthPlane(NS::UInteger resolveDepthPlane);
MTL::LoadAction loadAction() const;
void setLoadAction(MTL::LoadAction loadAction);
MTL::StoreAction storeAction() const;
void setStoreAction(MTL::StoreAction storeAction);
MTL::StoreActionOptions storeActionOptions() const;
void setStoreActionOptions(MTL::StoreActionOptions storeActionOptions);
};
class RenderPassColorAttachmentDescriptor : public NS::Copying<RenderPassColorAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor>
{
public:
static class RenderPassColorAttachmentDescriptor* alloc();
class RenderPassColorAttachmentDescriptor* init();
MTL::ClearColor clearColor() const;
void setClearColor(MTL::ClearColor clearColor);
};
_MTL_ENUM(NS::UInteger, MultisampleDepthResolveFilter) {
MultisampleDepthResolveFilterSample0 = 0,
MultisampleDepthResolveFilterMin = 1,
MultisampleDepthResolveFilterMax = 2,
};
class RenderPassDepthAttachmentDescriptor : public NS::Copying<RenderPassDepthAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor>
{
public:
static class RenderPassDepthAttachmentDescriptor* alloc();
class RenderPassDepthAttachmentDescriptor* init();
double clearDepth() const;
void setClearDepth(double clearDepth);
MTL::MultisampleDepthResolveFilter depthResolveFilter() const;
void setDepthResolveFilter(MTL::MultisampleDepthResolveFilter depthResolveFilter);
};
_MTL_ENUM(NS::UInteger, MultisampleStencilResolveFilter) {
MultisampleStencilResolveFilterSample0 = 0,
MultisampleStencilResolveFilterDepthResolvedSample = 1,
};
class RenderPassStencilAttachmentDescriptor : public NS::Copying<RenderPassStencilAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor>
{
public:
static class RenderPassStencilAttachmentDescriptor* alloc();
class RenderPassStencilAttachmentDescriptor* init();
uint32_t clearStencil() const;
void setClearStencil(uint32_t clearStencil);
MTL::MultisampleStencilResolveFilter stencilResolveFilter() const;
void setStencilResolveFilter(MTL::MultisampleStencilResolveFilter stencilResolveFilter);
};
class RenderPassColorAttachmentDescriptorArray : public NS::Referencing<RenderPassColorAttachmentDescriptorArray>
{
public:
static class RenderPassColorAttachmentDescriptorArray* alloc();
class RenderPassColorAttachmentDescriptorArray* init();
class RenderPassColorAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class RenderPassColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class RenderPassSampleBufferAttachmentDescriptor : public NS::Copying<RenderPassSampleBufferAttachmentDescriptor>
{
public:
static class RenderPassSampleBufferAttachmentDescriptor* alloc();
class RenderPassSampleBufferAttachmentDescriptor* init();
class CounterSampleBuffer* sampleBuffer() const;
void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer);
NS::UInteger startOfVertexSampleIndex() const;
void setStartOfVertexSampleIndex(NS::UInteger startOfVertexSampleIndex);
NS::UInteger endOfVertexSampleIndex() const;
void setEndOfVertexSampleIndex(NS::UInteger endOfVertexSampleIndex);
NS::UInteger startOfFragmentSampleIndex() const;
void setStartOfFragmentSampleIndex(NS::UInteger startOfFragmentSampleIndex);
NS::UInteger endOfFragmentSampleIndex() const;
void setEndOfFragmentSampleIndex(NS::UInteger endOfFragmentSampleIndex);
};
class RenderPassSampleBufferAttachmentDescriptorArray : public NS::Referencing<RenderPassSampleBufferAttachmentDescriptorArray>
{
public:
static class RenderPassSampleBufferAttachmentDescriptorArray* alloc();
class RenderPassSampleBufferAttachmentDescriptorArray* init();
class RenderPassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class RenderPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class RenderPassDescriptor : public NS::Copying<RenderPassDescriptor>
{
public:
static class RenderPassDescriptor* alloc();
class RenderPassDescriptor* init();
static class RenderPassDescriptor* renderPassDescriptor();
class RenderPassColorAttachmentDescriptorArray* colorAttachments() const;
class RenderPassDepthAttachmentDescriptor* depthAttachment() const;
void setDepthAttachment(const class RenderPassDepthAttachmentDescriptor* depthAttachment);
class RenderPassStencilAttachmentDescriptor* stencilAttachment() const;
void setStencilAttachment(const class RenderPassStencilAttachmentDescriptor* stencilAttachment);
class Buffer* visibilityResultBuffer() const;
void setVisibilityResultBuffer(const class Buffer* visibilityResultBuffer);
NS::UInteger renderTargetArrayLength() const;
void setRenderTargetArrayLength(NS::UInteger renderTargetArrayLength);
NS::UInteger imageblockSampleLength() const;
void setImageblockSampleLength(NS::UInteger imageblockSampleLength);
NS::UInteger threadgroupMemoryLength() const;
void setThreadgroupMemoryLength(NS::UInteger threadgroupMemoryLength);
NS::UInteger tileWidth() const;
void setTileWidth(NS::UInteger tileWidth);
NS::UInteger tileHeight() const;
void setTileHeight(NS::UInteger tileHeight);
NS::UInteger defaultRasterSampleCount() const;
void setDefaultRasterSampleCount(NS::UInteger defaultRasterSampleCount);
NS::UInteger renderTargetWidth() const;
void setRenderTargetWidth(NS::UInteger renderTargetWidth);
NS::UInteger renderTargetHeight() const;
void setRenderTargetHeight(NS::UInteger renderTargetHeight);
void setSamplePositions(const MTL::SamplePosition* positions, NS::UInteger count);
NS::UInteger getSamplePositions(MTL::SamplePosition* positions, NS::UInteger count);
class RasterizationRateMap* rasterizationRateMap() const;
void setRasterizationRateMap(const class RasterizationRateMap* rasterizationRateMap);
class RenderPassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const;
};
}
_MTL_INLINE MTL::ClearColor MTL::ClearColor::Make(double red, double green, double blue, double alpha)
{
return ClearColor(red, green, blue, alpha);
}
_MTL_INLINE MTL::ClearColor::ClearColor(double _red, double _green, double _blue, double _alpha)
: red(_red)
, green(_green)
, blue(_blue)
, alpha(_alpha)
{
}
_MTL_INLINE MTL::RenderPassAttachmentDescriptor* MTL::RenderPassAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPassAttachmentDescriptor* MTL::RenderPassAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPassAttachmentDescriptor>();
}
_MTL_INLINE MTL::Texture* MTL::RenderPassAttachmentDescriptor::texture() const
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(texture));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setTexture(const MTL::Texture* texture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_), texture);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::level() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(level));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setLevel(NS::UInteger level)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLevel_), level);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::slice() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(slice));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setSlice(NS::UInteger slice)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSlice_), slice);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::depthPlane() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depthPlane));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setDepthPlane(NS::UInteger depthPlane)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthPlane_), depthPlane);
}
_MTL_INLINE MTL::Texture* MTL::RenderPassAttachmentDescriptor::resolveTexture() const
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(resolveTexture));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveTexture(const MTL::Texture* resolveTexture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveTexture_), resolveTexture);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveLevel() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveLevel));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveLevel(NS::UInteger resolveLevel)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveLevel_), resolveLevel);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveSlice() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveSlice));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveSlice(NS::UInteger resolveSlice)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveSlice_), resolveSlice);
}
_MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveDepthPlane() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveDepthPlane));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveDepthPlane(NS::UInteger resolveDepthPlane)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveDepthPlane_), resolveDepthPlane);
}
_MTL_INLINE MTL::LoadAction MTL::RenderPassAttachmentDescriptor::loadAction() const
{
return Object::sendMessage<MTL::LoadAction>(this, _MTL_PRIVATE_SEL(loadAction));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setLoadAction(MTL::LoadAction loadAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLoadAction_), loadAction);
}
_MTL_INLINE MTL::StoreAction MTL::RenderPassAttachmentDescriptor::storeAction() const
{
return Object::sendMessage<MTL::StoreAction>(this, _MTL_PRIVATE_SEL(storeAction));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setStoreAction(MTL::StoreAction storeAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStoreAction_), storeAction);
}
_MTL_INLINE MTL::StoreActionOptions MTL::RenderPassAttachmentDescriptor::storeActionOptions() const
{
return Object::sendMessage<MTL::StoreActionOptions>(this, _MTL_PRIVATE_SEL(storeActionOptions));
}
_MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setStoreActionOptions(MTL::StoreActionOptions storeActionOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStoreActionOptions_), storeActionOptions);
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassColorAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPassColorAttachmentDescriptor>();
}
_MTL_INLINE MTL::ClearColor MTL::RenderPassColorAttachmentDescriptor::clearColor() const
{
return Object::sendMessage<MTL::ClearColor>(this, _MTL_PRIVATE_SEL(clearColor));
}
_MTL_INLINE void MTL::RenderPassColorAttachmentDescriptor::setClearColor(MTL::ClearColor clearColor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearColor_), clearColor);
}
_MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDepthAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassDepthAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassDepthAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDepthAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPassDepthAttachmentDescriptor>();
}
_MTL_INLINE double MTL::RenderPassDepthAttachmentDescriptor::clearDepth() const
{
return Object::sendMessage<double>(this, _MTL_PRIVATE_SEL(clearDepth));
}
_MTL_INLINE void MTL::RenderPassDepthAttachmentDescriptor::setClearDepth(double clearDepth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearDepth_), clearDepth);
}
_MTL_INLINE MTL::MultisampleDepthResolveFilter MTL::RenderPassDepthAttachmentDescriptor::depthResolveFilter() const
{
return Object::sendMessage<MTL::MultisampleDepthResolveFilter>(this, _MTL_PRIVATE_SEL(depthResolveFilter));
}
_MTL_INLINE void MTL::RenderPassDepthAttachmentDescriptor::setDepthResolveFilter(MTL::MultisampleDepthResolveFilter depthResolveFilter)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthResolveFilter_), depthResolveFilter);
}
_MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassStencilAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassStencilAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassStencilAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassStencilAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPassStencilAttachmentDescriptor>();
}
_MTL_INLINE uint32_t MTL::RenderPassStencilAttachmentDescriptor::clearStencil() const
{
return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(clearStencil));
}
_MTL_INLINE void MTL::RenderPassStencilAttachmentDescriptor::setClearStencil(uint32_t clearStencil)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearStencil_), clearStencil);
}
_MTL_INLINE MTL::MultisampleStencilResolveFilter MTL::RenderPassStencilAttachmentDescriptor::stencilResolveFilter() const
{
return Object::sendMessage<MTL::MultisampleStencilResolveFilter>(this, _MTL_PRIVATE_SEL(stencilResolveFilter));
}
_MTL_INLINE void MTL::RenderPassStencilAttachmentDescriptor::setStencilResolveFilter(MTL::MultisampleStencilResolveFilter stencilResolveFilter)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilResolveFilter_), stencilResolveFilter);
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassColorAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::RenderPassColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPassColorAttachmentDescriptorArray));
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassColorAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::RenderPassColorAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::RenderPassColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::RenderPassColorAttachmentDescriptorArray::setObject(const MTL::RenderPassColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassSampleBufferAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPassSampleBufferAttachmentDescriptor>();
}
_MTL_INLINE MTL::CounterSampleBuffer* MTL::RenderPassSampleBufferAttachmentDescriptor::sampleBuffer() const
{
return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer));
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer);
}
_MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::startOfVertexSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfVertexSampleIndex));
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setStartOfVertexSampleIndex(NS::UInteger startOfVertexSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfVertexSampleIndex_), startOfVertexSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::endOfVertexSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfVertexSampleIndex));
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setEndOfVertexSampleIndex(NS::UInteger endOfVertexSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfVertexSampleIndex_), endOfVertexSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::startOfFragmentSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfFragmentSampleIndex));
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setStartOfFragmentSampleIndex(NS::UInteger startOfFragmentSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfFragmentSampleIndex_), startOfFragmentSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::endOfFragmentSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfFragmentSampleIndex));
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setEndOfFragmentSampleIndex(NS::UInteger endOfFragmentSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfFragmentSampleIndex_), endOfFragmentSampleIndex);
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassSampleBufferAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::RenderPassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPassSampleBufferAttachmentDescriptorArray));
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassSampleBufferAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::RenderPassSampleBufferAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::RenderPassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptorArray::setObject(const MTL::RenderPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPassDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassDescriptor));
}
_MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::init()
{
return NS::Object::init<MTL::RenderPassDescriptor>();
}
_MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::renderPassDescriptor()
{
return Object::sendMessage<MTL::RenderPassDescriptor*>(_MTL_PRIVATE_CLS(MTLRenderPassDescriptor), _MTL_PRIVATE_SEL(renderPassDescriptor));
}
_MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassDescriptor::colorAttachments() const
{
return Object::sendMessage<MTL::RenderPassColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments));
}
_MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDescriptor::depthAttachment() const
{
return Object::sendMessage<MTL::RenderPassDepthAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(depthAttachment));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setDepthAttachment(const MTL::RenderPassDepthAttachmentDescriptor* depthAttachment)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthAttachment_), depthAttachment);
}
_MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassDescriptor::stencilAttachment() const
{
return Object::sendMessage<MTL::RenderPassStencilAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(stencilAttachment));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setStencilAttachment(const MTL::RenderPassStencilAttachmentDescriptor* stencilAttachment)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilAttachment_), stencilAttachment);
}
_MTL_INLINE MTL::Buffer* MTL::RenderPassDescriptor::visibilityResultBuffer() const
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(visibilityResultBuffer));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setVisibilityResultBuffer(const MTL::Buffer* visibilityResultBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibilityResultBuffer_), visibilityResultBuffer);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetArrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetArrayLength));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetArrayLength(NS::UInteger renderTargetArrayLength)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetArrayLength_), renderTargetArrayLength);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::imageblockSampleLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockSampleLength));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setImageblockSampleLength(NS::UInteger imageblockSampleLength)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockSampleLength_), imageblockSampleLength);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::threadgroupMemoryLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryLength));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setThreadgroupMemoryLength(NS::UInteger threadgroupMemoryLength)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_), threadgroupMemoryLength);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::tileWidth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileWidth));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setTileWidth(NS::UInteger tileWidth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileWidth_), tileWidth);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::tileHeight() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileHeight));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setTileHeight(NS::UInteger tileHeight)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileHeight_), tileHeight);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::defaultRasterSampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(defaultRasterSampleCount));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setDefaultRasterSampleCount(NS::UInteger defaultRasterSampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDefaultRasterSampleCount_), defaultRasterSampleCount);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetWidth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetWidth));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetWidth(NS::UInteger renderTargetWidth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetWidth_), renderTargetWidth);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetHeight() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetHeight));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetHeight(NS::UInteger renderTargetHeight)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetHeight_), renderTargetHeight);
}
_MTL_INLINE void MTL::RenderPassDescriptor::setSamplePositions(const MTL::SamplePosition* positions, NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplePositions_count_), positions, count);
}
_MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::getSamplePositions(MTL::SamplePosition* positions, NS::UInteger count)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(getSamplePositions_count_), positions, count);
}
_MTL_INLINE MTL::RasterizationRateMap* MTL::RenderPassDescriptor::rasterizationRateMap() const
{
return Object::sendMessage<MTL::RasterizationRateMap*>(this, _MTL_PRIVATE_SEL(rasterizationRateMap));
}
_MTL_INLINE void MTL::RenderPassDescriptor::setRasterizationRateMap(const MTL::RasterizationRateMap* rasterizationRateMap)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterizationRateMap_), rasterizationRateMap);
}
_MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassDescriptor::sampleBufferAttachments() const
{
return Object::sendMessage<MTL::RenderPassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments));
}
#pragma once
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, CompareFunction) {
CompareFunctionNever = 0,
CompareFunctionLess = 1,
CompareFunctionEqual = 2,
CompareFunctionLessEqual = 3,
CompareFunctionGreater = 4,
CompareFunctionNotEqual = 5,
CompareFunctionGreaterEqual = 6,
CompareFunctionAlways = 7,
};
_MTL_ENUM(NS::UInteger, StencilOperation) {
StencilOperationKeep = 0,
StencilOperationZero = 1,
StencilOperationReplace = 2,
StencilOperationIncrementClamp = 3,
StencilOperationDecrementClamp = 4,
StencilOperationInvert = 5,
StencilOperationIncrementWrap = 6,
StencilOperationDecrementWrap = 7,
};
class StencilDescriptor : public NS::Copying<StencilDescriptor>
{
public:
static class StencilDescriptor* alloc();
class StencilDescriptor* init();
MTL::CompareFunction stencilCompareFunction() const;
void setStencilCompareFunction(MTL::CompareFunction stencilCompareFunction);
MTL::StencilOperation stencilFailureOperation() const;
void setStencilFailureOperation(MTL::StencilOperation stencilFailureOperation);
MTL::StencilOperation depthFailureOperation() const;
void setDepthFailureOperation(MTL::StencilOperation depthFailureOperation);
MTL::StencilOperation depthStencilPassOperation() const;
void setDepthStencilPassOperation(MTL::StencilOperation depthStencilPassOperation);
uint32_t readMask() const;
void setReadMask(uint32_t readMask);
uint32_t writeMask() const;
void setWriteMask(uint32_t writeMask);
};
class DepthStencilDescriptor : public NS::Copying<DepthStencilDescriptor>
{
public:
static class DepthStencilDescriptor* alloc();
class DepthStencilDescriptor* init();
MTL::CompareFunction depthCompareFunction() const;
void setDepthCompareFunction(MTL::CompareFunction depthCompareFunction);
bool depthWriteEnabled() const;
void setDepthWriteEnabled(bool depthWriteEnabled);
class StencilDescriptor* frontFaceStencil() const;
void setFrontFaceStencil(const class StencilDescriptor* frontFaceStencil);
class StencilDescriptor* backFaceStencil() const;
void setBackFaceStencil(const class StencilDescriptor* backFaceStencil);
NS::String* label() const;
void setLabel(const NS::String* label);
};
class DepthStencilState : public NS::Referencing<DepthStencilState>
{
public:
NS::String* label() const;
class Device* device() const;
};
}
_MTL_INLINE MTL::StencilDescriptor* MTL::StencilDescriptor::alloc()
{
return NS::Object::alloc<MTL::StencilDescriptor>(_MTL_PRIVATE_CLS(MTLStencilDescriptor));
}
_MTL_INLINE MTL::StencilDescriptor* MTL::StencilDescriptor::init()
{
return NS::Object::init<MTL::StencilDescriptor>();
}
_MTL_INLINE MTL::CompareFunction MTL::StencilDescriptor::stencilCompareFunction() const
{
return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(stencilCompareFunction));
}
_MTL_INLINE void MTL::StencilDescriptor::setStencilCompareFunction(MTL::CompareFunction stencilCompareFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilCompareFunction_), stencilCompareFunction);
}
_MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::stencilFailureOperation() const
{
return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(stencilFailureOperation));
}
_MTL_INLINE void MTL::StencilDescriptor::setStencilFailureOperation(MTL::StencilOperation stencilFailureOperation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilFailureOperation_), stencilFailureOperation);
}
_MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::depthFailureOperation() const
{
return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(depthFailureOperation));
}
_MTL_INLINE void MTL::StencilDescriptor::setDepthFailureOperation(MTL::StencilOperation depthFailureOperation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthFailureOperation_), depthFailureOperation);
}
_MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::depthStencilPassOperation() const
{
return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(depthStencilPassOperation));
}
_MTL_INLINE void MTL::StencilDescriptor::setDepthStencilPassOperation(MTL::StencilOperation depthStencilPassOperation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStencilPassOperation_), depthStencilPassOperation);
}
_MTL_INLINE uint32_t MTL::StencilDescriptor::readMask() const
{
return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(readMask));
}
_MTL_INLINE void MTL::StencilDescriptor::setReadMask(uint32_t readMask)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setReadMask_), readMask);
}
_MTL_INLINE uint32_t MTL::StencilDescriptor::writeMask() const
{
return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(writeMask));
}
_MTL_INLINE void MTL::StencilDescriptor::setWriteMask(uint32_t writeMask)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWriteMask_), writeMask);
}
_MTL_INLINE MTL::DepthStencilDescriptor* MTL::DepthStencilDescriptor::alloc()
{
return NS::Object::alloc<MTL::DepthStencilDescriptor>(_MTL_PRIVATE_CLS(MTLDepthStencilDescriptor));
}
_MTL_INLINE MTL::DepthStencilDescriptor* MTL::DepthStencilDescriptor::init()
{
return NS::Object::init<MTL::DepthStencilDescriptor>();
}
_MTL_INLINE MTL::CompareFunction MTL::DepthStencilDescriptor::depthCompareFunction() const
{
return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(depthCompareFunction));
}
_MTL_INLINE void MTL::DepthStencilDescriptor::setDepthCompareFunction(MTL::CompareFunction depthCompareFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthCompareFunction_), depthCompareFunction);
}
_MTL_INLINE bool MTL::DepthStencilDescriptor::depthWriteEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthWriteEnabled));
}
_MTL_INLINE void MTL::DepthStencilDescriptor::setDepthWriteEnabled(bool depthWriteEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthWriteEnabled_), depthWriteEnabled);
}
_MTL_INLINE MTL::StencilDescriptor* MTL::DepthStencilDescriptor::frontFaceStencil() const
{
return Object::sendMessage<MTL::StencilDescriptor*>(this, _MTL_PRIVATE_SEL(frontFaceStencil));
}
_MTL_INLINE void MTL::DepthStencilDescriptor::setFrontFaceStencil(const MTL::StencilDescriptor* frontFaceStencil)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFrontFaceStencil_), frontFaceStencil);
}
_MTL_INLINE MTL::StencilDescriptor* MTL::DepthStencilDescriptor::backFaceStencil() const
{
return Object::sendMessage<MTL::StencilDescriptor*>(this, _MTL_PRIVATE_SEL(backFaceStencil));
}
_MTL_INLINE void MTL::DepthStencilDescriptor::setBackFaceStencil(const MTL::StencilDescriptor* backFaceStencil)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBackFaceStencil_), backFaceStencil);
}
_MTL_INLINE NS::String* MTL::DepthStencilDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::DepthStencilDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE NS::String* MTL::DepthStencilState::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::Device* MTL::DepthStencilState::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
namespace MTL
{
_MTL_ENUM(NS::UInteger, SamplerMinMagFilter) {
SamplerMinMagFilterNearest = 0,
SamplerMinMagFilterLinear = 1,
};
_MTL_ENUM(NS::UInteger, SamplerMipFilter) {
SamplerMipFilterNotMipmapped = 0,
SamplerMipFilterNearest = 1,
SamplerMipFilterLinear = 2,
};
_MTL_ENUM(NS::UInteger, SamplerAddressMode) {
SamplerAddressModeClampToEdge = 0,
SamplerAddressModeMirrorClampToEdge = 1,
SamplerAddressModeRepeat = 2,
SamplerAddressModeMirrorRepeat = 3,
SamplerAddressModeClampToZero = 4,
SamplerAddressModeClampToBorderColor = 5,
};
_MTL_ENUM(NS::UInteger, SamplerBorderColor) {
SamplerBorderColorTransparentBlack = 0,
SamplerBorderColorOpaqueBlack = 1,
SamplerBorderColorOpaqueWhite = 2,
};
class SamplerDescriptor : public NS::Copying<SamplerDescriptor>
{
public:
static class SamplerDescriptor* alloc();
class SamplerDescriptor* init();
MTL::SamplerMinMagFilter minFilter() const;
void setMinFilter(MTL::SamplerMinMagFilter minFilter);
MTL::SamplerMinMagFilter magFilter() const;
void setMagFilter(MTL::SamplerMinMagFilter magFilter);
MTL::SamplerMipFilter mipFilter() const;
void setMipFilter(MTL::SamplerMipFilter mipFilter);
NS::UInteger maxAnisotropy() const;
void setMaxAnisotropy(NS::UInteger maxAnisotropy);
MTL::SamplerAddressMode sAddressMode() const;
void setSAddressMode(MTL::SamplerAddressMode sAddressMode);
MTL::SamplerAddressMode tAddressMode() const;
void setTAddressMode(MTL::SamplerAddressMode tAddressMode);
MTL::SamplerAddressMode rAddressMode() const;
void setRAddressMode(MTL::SamplerAddressMode rAddressMode);
MTL::SamplerBorderColor borderColor() const;
void setBorderColor(MTL::SamplerBorderColor borderColor);
bool normalizedCoordinates() const;
void setNormalizedCoordinates(bool normalizedCoordinates);
float lodMinClamp() const;
void setLodMinClamp(float lodMinClamp);
float lodMaxClamp() const;
void setLodMaxClamp(float lodMaxClamp);
bool lodAverage() const;
void setLodAverage(bool lodAverage);
MTL::CompareFunction compareFunction() const;
void setCompareFunction(MTL::CompareFunction compareFunction);
bool supportArgumentBuffers() const;
void setSupportArgumentBuffers(bool supportArgumentBuffers);
NS::String* label() const;
void setLabel(const NS::String* label);
};
class SamplerState : public NS::Referencing<SamplerState>
{
public:
NS::String* label() const;
class Device* device() const;
};
}
_MTL_INLINE MTL::SamplerDescriptor* MTL::SamplerDescriptor::alloc()
{
return NS::Object::alloc<MTL::SamplerDescriptor>(_MTL_PRIVATE_CLS(MTLSamplerDescriptor));
}
_MTL_INLINE MTL::SamplerDescriptor* MTL::SamplerDescriptor::init()
{
return NS::Object::init<MTL::SamplerDescriptor>();
}
_MTL_INLINE MTL::SamplerMinMagFilter MTL::SamplerDescriptor::minFilter() const
{
return Object::sendMessage<MTL::SamplerMinMagFilter>(this, _MTL_PRIVATE_SEL(minFilter));
}
_MTL_INLINE void MTL::SamplerDescriptor::setMinFilter(MTL::SamplerMinMagFilter minFilter)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMinFilter_), minFilter);
}
_MTL_INLINE MTL::SamplerMinMagFilter MTL::SamplerDescriptor::magFilter() const
{
return Object::sendMessage<MTL::SamplerMinMagFilter>(this, _MTL_PRIVATE_SEL(magFilter));
}
_MTL_INLINE void MTL::SamplerDescriptor::setMagFilter(MTL::SamplerMinMagFilter magFilter)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMagFilter_), magFilter);
}
_MTL_INLINE MTL::SamplerMipFilter MTL::SamplerDescriptor::mipFilter() const
{
return Object::sendMessage<MTL::SamplerMipFilter>(this, _MTL_PRIVATE_SEL(mipFilter));
}
_MTL_INLINE void MTL::SamplerDescriptor::setMipFilter(MTL::SamplerMipFilter mipFilter)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMipFilter_), mipFilter);
}
_MTL_INLINE NS::UInteger MTL::SamplerDescriptor::maxAnisotropy() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxAnisotropy));
}
_MTL_INLINE void MTL::SamplerDescriptor::setMaxAnisotropy(NS::UInteger maxAnisotropy)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxAnisotropy_), maxAnisotropy);
}
_MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::sAddressMode() const
{
return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(sAddressMode));
}
_MTL_INLINE void MTL::SamplerDescriptor::setSAddressMode(MTL::SamplerAddressMode sAddressMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSAddressMode_), sAddressMode);
}
_MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::tAddressMode() const
{
return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(tAddressMode));
}
_MTL_INLINE void MTL::SamplerDescriptor::setTAddressMode(MTL::SamplerAddressMode tAddressMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTAddressMode_), tAddressMode);
}
_MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::rAddressMode() const
{
return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(rAddressMode));
}
_MTL_INLINE void MTL::SamplerDescriptor::setRAddressMode(MTL::SamplerAddressMode rAddressMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRAddressMode_), rAddressMode);
}
_MTL_INLINE MTL::SamplerBorderColor MTL::SamplerDescriptor::borderColor() const
{
return Object::sendMessage<MTL::SamplerBorderColor>(this, _MTL_PRIVATE_SEL(borderColor));
}
_MTL_INLINE void MTL::SamplerDescriptor::setBorderColor(MTL::SamplerBorderColor borderColor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBorderColor_), borderColor);
}
_MTL_INLINE bool MTL::SamplerDescriptor::normalizedCoordinates() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(normalizedCoordinates));
}
_MTL_INLINE void MTL::SamplerDescriptor::setNormalizedCoordinates(bool normalizedCoordinates)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setNormalizedCoordinates_), normalizedCoordinates);
}
_MTL_INLINE float MTL::SamplerDescriptor::lodMinClamp() const
{
return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(lodMinClamp));
}
_MTL_INLINE void MTL::SamplerDescriptor::setLodMinClamp(float lodMinClamp)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodMinClamp_), lodMinClamp);
}
_MTL_INLINE float MTL::SamplerDescriptor::lodMaxClamp() const
{
return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(lodMaxClamp));
}
_MTL_INLINE void MTL::SamplerDescriptor::setLodMaxClamp(float lodMaxClamp)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodMaxClamp_), lodMaxClamp);
}
_MTL_INLINE bool MTL::SamplerDescriptor::lodAverage() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(lodAverage));
}
_MTL_INLINE void MTL::SamplerDescriptor::setLodAverage(bool lodAverage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodAverage_), lodAverage);
}
_MTL_INLINE MTL::CompareFunction MTL::SamplerDescriptor::compareFunction() const
{
return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(compareFunction));
}
_MTL_INLINE void MTL::SamplerDescriptor::setCompareFunction(MTL::CompareFunction compareFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCompareFunction_), compareFunction);
}
_MTL_INLINE bool MTL::SamplerDescriptor::supportArgumentBuffers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportArgumentBuffers));
}
_MTL_INLINE void MTL::SamplerDescriptor::setSupportArgumentBuffers(bool supportArgumentBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportArgumentBuffers_), supportArgumentBuffers);
}
_MTL_INLINE NS::String* MTL::SamplerDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::SamplerDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE NS::String* MTL::SamplerState::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::Device* MTL::SamplerState::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
namespace MTL
{
_MTL_ENUM(NS::UInteger, PrimitiveType) {
PrimitiveTypePoint = 0,
PrimitiveTypeLine = 1,
PrimitiveTypeLineStrip = 2,
PrimitiveTypeTriangle = 3,
PrimitiveTypeTriangleStrip = 4,
};
_MTL_ENUM(NS::UInteger, VisibilityResultMode) {
VisibilityResultModeDisabled = 0,
VisibilityResultModeBoolean = 1,
VisibilityResultModeCounting = 2,
};
struct ScissorRect
{
NS::UInteger x;
NS::UInteger y;
NS::UInteger width;
NS::UInteger height;
} _MTL_PACKED;
struct Viewport
{
double originX;
double originY;
double width;
double height;
double znear;
double zfar;
} _MTL_PACKED;
_MTL_ENUM(NS::UInteger, CullMode) {
CullModeNone = 0,
CullModeFront = 1,
CullModeBack = 2,
};
_MTL_ENUM(NS::UInteger, Winding) {
WindingClockwise = 0,
WindingCounterClockwise = 1,
};
_MTL_ENUM(NS::UInteger, DepthClipMode) {
DepthClipModeClip = 0,
DepthClipModeClamp = 1,
};
_MTL_ENUM(NS::UInteger, TriangleFillMode) {
TriangleFillModeFill = 0,
TriangleFillModeLines = 1,
};
struct DrawPrimitivesIndirectArguments
{
uint32_t vertexCount;
uint32_t instanceCount;
uint32_t vertexStart;
uint32_t baseInstance;
} _MTL_PACKED;
struct DrawIndexedPrimitivesIndirectArguments
{
uint32_t indexCount;
uint32_t instanceCount;
uint32_t indexStart;
int32_t baseVertex;
uint32_t baseInstance;
} _MTL_PACKED;
struct VertexAmplificationViewMapping
{
uint32_t viewportArrayIndexOffset;
uint32_t renderTargetArrayIndexOffset;
} _MTL_PACKED;
struct DrawPatchIndirectArguments
{
uint32_t patchCount;
uint32_t instanceCount;
uint32_t patchStart;
uint32_t baseInstance;
} _MTL_PACKED;
struct QuadTessellationFactorsHalf
{
uint16_t edgeTessellationFactor[4];
uint16_t insideTessellationFactor[2];
} _MTL_PACKED;
struct TriangleTessellationFactorsHalf
{
uint16_t edgeTessellationFactor[3];
uint16_t insideTessellationFactor;
} _MTL_PACKED;
_MTL_OPTIONS(NS::UInteger, RenderStages) {
RenderStageVertex = 1,
RenderStageFragment = 2,
RenderStageTile = 4,
};
class RenderCommandEncoder : public NS::Referencing<RenderCommandEncoder, CommandEncoder>
{
public:
void setRenderPipelineState(const class RenderPipelineState* pipelineState);
void setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger index);
void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setVertexBufferOffset(NS::UInteger offset, NS::UInteger index);
void setVertexBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range);
void setVertexTexture(const class Texture* texture, NS::UInteger index);
void setVertexTextures(MTL::Texture* textures[], NS::Range range);
void setVertexSamplerState(const class SamplerState* sampler, NS::UInteger index);
void setVertexSamplerStates(MTL::SamplerState* samplers[], NS::Range range);
void setVertexSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index);
void setVertexSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range);
void setVertexVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex);
void setVertexVisibleFunctionTables(const class VisibleFunctionTable* functionTables[], NS::Range range);
void setVertexIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex);
void setVertexIntersectionFunctionTables(const class IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range);
void setVertexAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex);
void setViewport(MTL::Viewport viewport);
void setViewports(const MTL::Viewport* viewports, NS::UInteger count);
void setFrontFacingWinding(MTL::Winding frontFacingWinding);
void setVertexAmplificationCount(NS::UInteger count, const MTL::VertexAmplificationViewMapping* viewMappings);
void setCullMode(MTL::CullMode cullMode);
void setDepthClipMode(MTL::DepthClipMode depthClipMode);
void setDepthBias(float depthBias, float slopeScale, float clamp);
void setScissorRect(MTL::ScissorRect rect);
void setScissorRects(const MTL::ScissorRect* scissorRects, NS::UInteger count);
void setTriangleFillMode(MTL::TriangleFillMode fillMode);
void setFragmentBytes(const void* bytes, NS::UInteger length, NS::UInteger index);
void setFragmentBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setFragmentBufferOffset(NS::UInteger offset, NS::UInteger index);
void setFragmentBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range);
void setFragmentTexture(const class Texture* texture, NS::UInteger index);
void setFragmentTextures(MTL::Texture* textures[], NS::Range range);
void setFragmentSamplerState(const class SamplerState* sampler, NS::UInteger index);
void setFragmentSamplerStates(MTL::SamplerState* samplers[], NS::Range range);
void setFragmentSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index);
void setFragmentSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range);
void setFragmentVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex);
void setFragmentVisibleFunctionTables(const VisibleFunctionTable* functionTables[], NS::Range range);
void setFragmentIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex);
void setFragmentIntersectionFunctionTables(const class IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range);
void setFragmentAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex);
void setBlendColorRed(float red, float green, float blue, float alpha);
void setDepthStencilState(const class DepthStencilState* depthStencilState);
void setStencilReferenceValue(uint32_t referenceValue);
void setStencilFrontReferenceValue(uint32_t frontReferenceValue, uint32_t backReferenceValue);
void setVisibilityResultMode(MTL::VisibilityResultMode mode, NS::UInteger offset);
void setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex);
void setDepthStoreAction(MTL::StoreAction storeAction);
void setStencilStoreAction(MTL::StoreAction storeAction);
void setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex);
void setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions);
void setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions);
void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount);
void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount);
void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount);
void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset);
void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance);
void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance);
void drawPrimitives(MTL::PrimitiveType primitiveType, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
void textureBarrier();
void updateFence(const class Fence* fence, MTL::RenderStages stages);
void waitForFence(const class Fence* fence, MTL::RenderStages stages);
void setTessellationFactorBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride);
void setTessellationFactorScale(float scale);
void drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance);
void drawPatches(NS::UInteger numberOfPatchControlPoints, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance);
void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
NS::UInteger tileWidth() const;
NS::UInteger tileHeight() const;
void setTileBytes(const void* bytes, NS::UInteger length, NS::UInteger index);
void setTileBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setTileBufferOffset(NS::UInteger offset, NS::UInteger index);
void setTileBuffers(MTL::Buffer* buffers, const NS::UInteger* offsets, NS::Range range);
void setTileTexture(const class Texture* texture, NS::UInteger index);
void setTileTextures(MTL::Texture* textures[], NS::Range range);
void setTileSamplerState(const class SamplerState* sampler, NS::UInteger index);
void setTileSamplerStates(MTL::SamplerState* samplers[], NS::Range range);
void setTileSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index);
void setTileSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range);
void setTileVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex);
void setTileVisibleFunctionTables(const class VisibleFunctionTable* functionTables[], NS::Range range);
void setTileIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex);
void setTileIntersectionFunctionTables(const class IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range);
void setTileAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex);
void dispatchThreadsPerTile(MTL::Size threadsPerTile);
void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger offset, NS::UInteger index);
void useResource(const class Resource* resource, MTL::ResourceUsage usage);
void useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage);
void useResource(const class Resource* resource, MTL::ResourceUsage usage, MTL::RenderStages stages);
void useResources(MTL::Resource* resources, NS::UInteger count, MTL::ResourceUsage usage, MTL::RenderStages stages);
void useHeap(const class Heap* heap);
void useHeaps(MTL::Heap* heaps[], NS::UInteger count);
void useHeap(const class Heap* heap, MTL::RenderStages stages);
void useHeaps(MTL::Heap* heaps[], NS::UInteger count, MTL::RenderStages stages);
void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange);
void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandbuffer, const class Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset);
void memoryBarrier(MTL::BarrierScope scope, MTL::RenderStages after, MTL::RenderStages before);
void memoryBarrier(MTL::Resource* resources[], NS::UInteger count, MTL::RenderStages after, MTL::RenderStages before);
void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier);
};
}
_MTL_INLINE void MTL::RenderCommandEncoder::setRenderPipelineState(const MTL::RenderPipelineState* pipelineState)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_), pipelineState);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBytes_length_atIndex_), bytes, length, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexBufferOffset(NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBufferOffset_atIndex_), offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexTexture(const MTL::Texture* texture, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexTexture_atIndex_), texture, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexTextures(MTL::Texture* textures[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexTextures_withRange_), textures, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerState(const MTL::SamplerState* sampler, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerState_atIndex_), sampler, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerStates(MTL::SamplerState* samplers[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerStates_withRange_), samplers, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexVisibleFunctionTables(const MTL::VisibleFunctionTable* functionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexVisibleFunctionTables_withBufferRange_), functionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexIntersectionFunctionTables(const MTL::IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setViewport(MTL::Viewport viewport)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setViewport_), viewport);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setViewports(const MTL::Viewport* viewports, NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setViewports_count_), viewports, count);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFrontFacingWinding(MTL::Winding frontFacingWinding)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFrontFacingWinding_), frontFacingWinding);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVertexAmplificationCount(NS::UInteger count, const MTL::VertexAmplificationViewMapping* viewMappings)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAmplificationCount_viewMappings_), count, viewMappings);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setCullMode(MTL::CullMode cullMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCullMode_), cullMode);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setDepthClipMode(MTL::DepthClipMode depthClipMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthClipMode_), depthClipMode);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setDepthBias(float depthBias, float slopeScale, float clamp)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthBias_slopeScale_clamp_), depthBias, slopeScale, clamp);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setScissorRect(MTL::ScissorRect rect)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScissorRect_), rect);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setScissorRects(const MTL::ScissorRect* scissorRects, NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScissorRects_count_), scissorRects, count);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTriangleFillMode(MTL::TriangleFillMode fillMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleFillMode_), fillMode);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBytes(const void* bytes, NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBytes_length_atIndex_), bytes, length, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBufferOffset(NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBufferOffset_atIndex_), offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentTexture(const MTL::Texture* texture, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentTexture_atIndex_), texture, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentTextures(MTL::Texture* textures[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentTextures_withRange_), textures, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerState(const MTL::SamplerState* sampler, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerState_atIndex_), sampler, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerStates(MTL::SamplerState* samplers[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerStates_withRange_), samplers, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentVisibleFunctionTables(const MTL::VisibleFunctionTable* functionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentVisibleFunctionTables_withBufferRange_), functionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentIntersectionFunctionTables(const MTL::IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setFragmentAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setBlendColorRed(float red, float green, float blue, float alpha)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBlendColorRed_green_blue_alpha_), red, green, blue, alpha);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setDepthStencilState(const MTL::DepthStencilState* depthStencilState)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStencilState_), depthStencilState);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setStencilReferenceValue(uint32_t referenceValue)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilReferenceValue_), referenceValue);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setStencilFrontReferenceValue(uint32_t frontReferenceValue, uint32_t backReferenceValue)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilFrontReferenceValue_backReferenceValue_), frontReferenceValue, backReferenceValue);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setVisibilityResultMode(MTL::VisibilityResultMode mode, NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibilityResultMode_offset_), mode, offset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreAction_atIndex_), storeAction, colorAttachmentIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setDepthStoreAction(MTL::StoreAction storeAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreAction_), storeAction);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setStencilStoreAction(MTL::StoreAction storeAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreAction_), storeAction);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreActionOptions_atIndex_), storeActionOptions, colorAttachmentIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreActionOptions_), storeActionOptions);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreActionOptions_), storeActionOptions);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_), primitiveType, vertexStart, vertexCount, instanceCount);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_), primitiveType, vertexStart, vertexCount);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_), primitiveType, vertexStart, vertexCount, instanceCount, baseInstance);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount, baseVertex, baseInstance);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_indirectBuffer_indirectBufferOffset_), primitiveType, indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset_), primitiveType, indexType, indexBuffer, indexBufferOffset, indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::textureBarrier()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(textureBarrier));
}
_MTL_INLINE void MTL::RenderCommandEncoder::updateFence(const MTL::Fence* fence, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_afterStages_), fence, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::waitForFence(const MTL::Fence* fence, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_beforeStages_), fence, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTessellationFactorBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorBuffer_offset_instanceStride_), buffer, offset, instanceStride);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTessellationFactorScale(float scale)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorScale_), scale);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, instanceCount, baseInstance);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawPatches(NS::UInteger numberOfPatchControlPoints, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchIndexBuffer_patchIndexBufferOffset_indirectBuffer_indirectBufferOffset_), numberOfPatchControlPoints, patchIndexBuffer, patchIndexBufferOffset, indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, instanceCount, baseInstance);
}
_MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_indirectBuffer_indirectBufferOffset_), numberOfPatchControlPoints, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE NS::UInteger MTL::RenderCommandEncoder::tileWidth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileWidth));
}
_MTL_INLINE NS::UInteger MTL::RenderCommandEncoder::tileHeight() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileHeight));
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileBytes(const void* bytes, NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBytes_length_atIndex_), bytes, length, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileBufferOffset(NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBufferOffset_atIndex_), offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileBuffers(MTL::Buffer* buffers, const NS::UInteger* offsets, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileTexture(const MTL::Texture* texture, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileTexture_atIndex_), texture, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileTextures(MTL::Texture* textures[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileTextures_withRange_), textures, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerState(const MTL::SamplerState* sampler, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerState_atIndex_), sampler, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerStates(MTL::SamplerState* samplers[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerStates_withRange_), samplers, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileVisibleFunctionTables(const MTL::VisibleFunctionTable* functionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileVisibleFunctionTables_withBufferRange_), functionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileIntersectionFunctionTables(const MTL::IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setTileAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex);
}
_MTL_INLINE void MTL::RenderCommandEncoder::dispatchThreadsPerTile(MTL::Size threadsPerTile)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadsPerTile_), threadsPerTile);
}
_MTL_INLINE void MTL::RenderCommandEncoder::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_offset_atIndex_), length, offset, index);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_stages_), resource, usage, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useResources(MTL::Resource* resources, NS::UInteger count, MTL::ResourceUsage usage, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_stages_), resources, count, usage, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useHeap(const MTL::Heap* heap)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useHeaps(MTL::Heap* heaps[], NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useHeap(const MTL::Heap* heap, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_stages_), heap, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::useHeaps(MTL::Heap* heaps[], NS::UInteger count, MTL::RenderStages stages)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_stages_), heaps, count, stages);
}
_MTL_INLINE void MTL::RenderCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_withRange_), indirectCommandBuffer, executionRange);
}
_MTL_INLINE void MTL::RenderCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandbuffer, const MTL::Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_), indirectCommandbuffer, indirectRangeBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::RenderCommandEncoder::memoryBarrier(MTL::BarrierScope scope, MTL::RenderStages after, MTL::RenderStages before)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithScope_afterStages_beforeStages_), scope, after, before);
}
_MTL_INLINE void MTL::RenderCommandEncoder::memoryBarrier(MTL::Resource* resources[], NS::UInteger count, MTL::RenderStages after, MTL::RenderStages before)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithResources_count_afterStages_beforeStages_), resources, count, after, before);
}
_MTL_INLINE void MTL::RenderCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier);
}
namespace MTL
{
_MTL_ENUM(NS::UInteger, BlendFactor) {
BlendFactorZero = 0,
BlendFactorOne = 1,
BlendFactorSourceColor = 2,
BlendFactorOneMinusSourceColor = 3,
BlendFactorSourceAlpha = 4,
BlendFactorOneMinusSourceAlpha = 5,
BlendFactorDestinationColor = 6,
BlendFactorOneMinusDestinationColor = 7,
BlendFactorDestinationAlpha = 8,
BlendFactorOneMinusDestinationAlpha = 9,
BlendFactorSourceAlphaSaturated = 10,
BlendFactorBlendColor = 11,
BlendFactorOneMinusBlendColor = 12,
BlendFactorBlendAlpha = 13,
BlendFactorOneMinusBlendAlpha = 14,
BlendFactorSource1Color = 15,
BlendFactorOneMinusSource1Color = 16,
BlendFactorSource1Alpha = 17,
BlendFactorOneMinusSource1Alpha = 18,
};
_MTL_ENUM(NS::UInteger, BlendOperation) {
BlendOperationAdd = 0,
BlendOperationSubtract = 1,
BlendOperationReverseSubtract = 2,
BlendOperationMin = 3,
BlendOperationMax = 4,
};
_MTL_OPTIONS(NS::UInteger, ColorWriteMask) {
ColorWriteMaskNone = 0,
ColorWriteMaskAlpha = 1,
ColorWriteMaskBlue = 2,
ColorWriteMaskGreen = 4,
ColorWriteMaskRed = 8,
ColorWriteMaskAll = 15,
};
_MTL_ENUM(NS::UInteger, PrimitiveTopologyClass) {
PrimitiveTopologyClassUnspecified = 0,
PrimitiveTopologyClassPoint = 1,
PrimitiveTopologyClassLine = 2,
PrimitiveTopologyClassTriangle = 3,
};
_MTL_ENUM(NS::UInteger, TessellationPartitionMode) {
TessellationPartitionModePow2 = 0,
TessellationPartitionModeInteger = 1,
TessellationPartitionModeFractionalOdd = 2,
TessellationPartitionModeFractionalEven = 3,
};
_MTL_ENUM(NS::UInteger, TessellationFactorStepFunction) {
TessellationFactorStepFunctionConstant = 0,
TessellationFactorStepFunctionPerPatch = 1,
TessellationFactorStepFunctionPerInstance = 2,
TessellationFactorStepFunctionPerPatchAndPerInstance = 3,
};
_MTL_ENUM(NS::UInteger, TessellationFactorFormat) {
TessellationFactorFormatHalf = 0,
};
_MTL_ENUM(NS::UInteger, TessellationControlPointIndexType) {
TessellationControlPointIndexTypeNone = 0,
TessellationControlPointIndexTypeUInt16 = 1,
TessellationControlPointIndexTypeUInt32 = 2,
};
class RenderPipelineColorAttachmentDescriptor : public NS::Copying<RenderPipelineColorAttachmentDescriptor>
{
public:
static class RenderPipelineColorAttachmentDescriptor* alloc();
class RenderPipelineColorAttachmentDescriptor* init();
MTL::PixelFormat pixelFormat() const;
void setPixelFormat(MTL::PixelFormat pixelFormat);
bool blendingEnabled() const;
void setBlendingEnabled(bool blendingEnabled);
MTL::BlendFactor sourceRGBBlendFactor() const;
void setSourceRGBBlendFactor(MTL::BlendFactor sourceRGBBlendFactor);
MTL::BlendFactor destinationRGBBlendFactor() const;
void setDestinationRGBBlendFactor(MTL::BlendFactor destinationRGBBlendFactor);
MTL::BlendOperation rgbBlendOperation() const;
void setRgbBlendOperation(MTL::BlendOperation rgbBlendOperation);
MTL::BlendFactor sourceAlphaBlendFactor() const;
void setSourceAlphaBlendFactor(MTL::BlendFactor sourceAlphaBlendFactor);
MTL::BlendFactor destinationAlphaBlendFactor() const;
void setDestinationAlphaBlendFactor(MTL::BlendFactor destinationAlphaBlendFactor);
MTL::BlendOperation alphaBlendOperation() const;
void setAlphaBlendOperation(MTL::BlendOperation alphaBlendOperation);
MTL::ColorWriteMask writeMask() const;
void setWriteMask(MTL::ColorWriteMask writeMask);
};
class RenderPipelineReflection : public NS::Referencing<RenderPipelineReflection>
{
public:
static class RenderPipelineReflection* alloc();
class RenderPipelineReflection* init();
NS::Array* vertexArguments() const;
NS::Array* fragmentArguments() const;
NS::Array* tileArguments() const;
};
class RenderPipelineDescriptor : public NS::Copying<RenderPipelineDescriptor>
{
public:
static class RenderPipelineDescriptor* alloc();
class RenderPipelineDescriptor* init();
NS::String* label() const;
void setLabel(const NS::String* label);
class Function* vertexFunction() const;
void setVertexFunction(const class Function* vertexFunction);
class Function* fragmentFunction() const;
void setFragmentFunction(const class Function* fragmentFunction);
class VertexDescriptor* vertexDescriptor() const;
void setVertexDescriptor(const class VertexDescriptor* vertexDescriptor);
NS::UInteger sampleCount() const;
void setSampleCount(NS::UInteger sampleCount);
NS::UInteger rasterSampleCount() const;
void setRasterSampleCount(NS::UInteger rasterSampleCount);
bool alphaToCoverageEnabled() const;
void setAlphaToCoverageEnabled(bool alphaToCoverageEnabled);
bool alphaToOneEnabled() const;
void setAlphaToOneEnabled(bool alphaToOneEnabled);
bool rasterizationEnabled() const;
void setRasterizationEnabled(bool rasterizationEnabled);
NS::UInteger maxVertexAmplificationCount() const;
void setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount);
class RenderPipelineColorAttachmentDescriptorArray* colorAttachments() const;
MTL::PixelFormat depthAttachmentPixelFormat() const;
void setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat);
MTL::PixelFormat stencilAttachmentPixelFormat() const;
void setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat);
MTL::PrimitiveTopologyClass inputPrimitiveTopology() const;
void setInputPrimitiveTopology(MTL::PrimitiveTopologyClass inputPrimitiveTopology);
MTL::TessellationPartitionMode tessellationPartitionMode() const;
void setTessellationPartitionMode(MTL::TessellationPartitionMode tessellationPartitionMode);
NS::UInteger maxTessellationFactor() const;
void setMaxTessellationFactor(NS::UInteger maxTessellationFactor);
bool tessellationFactorScaleEnabled() const;
void setTessellationFactorScaleEnabled(bool tessellationFactorScaleEnabled);
MTL::TessellationFactorFormat tessellationFactorFormat() const;
void setTessellationFactorFormat(MTL::TessellationFactorFormat tessellationFactorFormat);
MTL::TessellationControlPointIndexType tessellationControlPointIndexType() const;
void setTessellationControlPointIndexType(MTL::TessellationControlPointIndexType tessellationControlPointIndexType);
MTL::TessellationFactorStepFunction tessellationFactorStepFunction() const;
void setTessellationFactorStepFunction(MTL::TessellationFactorStepFunction tessellationFactorStepFunction);
MTL::Winding tessellationOutputWindingOrder() const;
void setTessellationOutputWindingOrder(MTL::Winding tessellationOutputWindingOrder);
class PipelineBufferDescriptorArray* vertexBuffers() const;
class PipelineBufferDescriptorArray* fragmentBuffers() const;
bool supportIndirectCommandBuffers() const;
void setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers);
NS::Array* binaryArchives() const;
void setBinaryArchives(const NS::Array* binaryArchives);
NS::Array* vertexPreloadedLibraries() const;
void setVertexPreloadedLibraries(const NS::Array* vertexPreloadedLibraries);
NS::Array* fragmentPreloadedLibraries() const;
void setFragmentPreloadedLibraries(const NS::Array* fragmentPreloadedLibraries);
class LinkedFunctions* vertexLinkedFunctions() const;
void setVertexLinkedFunctions(const class LinkedFunctions* vertexLinkedFunctions);
class LinkedFunctions* fragmentLinkedFunctions() const;
void setFragmentLinkedFunctions(const class LinkedFunctions* fragmentLinkedFunctions);
bool supportAddingVertexBinaryFunctions() const;
void setSupportAddingVertexBinaryFunctions(bool supportAddingVertexBinaryFunctions);
bool supportAddingFragmentBinaryFunctions() const;
void setSupportAddingFragmentBinaryFunctions(bool supportAddingFragmentBinaryFunctions);
NS::UInteger maxVertexCallStackDepth() const;
void setMaxVertexCallStackDepth(NS::UInteger maxVertexCallStackDepth);
NS::UInteger maxFragmentCallStackDepth() const;
void setMaxFragmentCallStackDepth(NS::UInteger maxFragmentCallStackDepth);
void reset();
};
class RenderPipelineFunctionsDescriptor : public NS::Copying<RenderPipelineFunctionsDescriptor>
{
public:
static class RenderPipelineFunctionsDescriptor* alloc();
class RenderPipelineFunctionsDescriptor* init();
NS::Array* vertexAdditionalBinaryFunctions() const;
void setVertexAdditionalBinaryFunctions(const NS::Array* vertexAdditionalBinaryFunctions);
NS::Array* fragmentAdditionalBinaryFunctions() const;
void setFragmentAdditionalBinaryFunctions(const NS::Array* fragmentAdditionalBinaryFunctions);
NS::Array* tileAdditionalBinaryFunctions() const;
void setTileAdditionalBinaryFunctions(const NS::Array* tileAdditionalBinaryFunctions);
};
class RenderPipelineState : public NS::Referencing<RenderPipelineState>
{
public:
NS::String* label() const;
class Device* device() const;
NS::UInteger maxTotalThreadsPerThreadgroup() const;
bool threadgroupSizeMatchesTileSize() const;
NS::UInteger imageblockSampleLength() const;
NS::UInteger imageblockMemoryLength(MTL::Size imageblockDimensions);
bool supportIndirectCommandBuffers() const;
class FunctionHandle* functionHandle(const class Function* function, MTL::RenderStages stage);
class VisibleFunctionTable* newVisibleFunctionTable(const class VisibleFunctionTableDescriptor* descriptor, MTL::RenderStages stage);
class IntersectionFunctionTable* newIntersectionFunctionTable(const class IntersectionFunctionTableDescriptor* descriptor, MTL::RenderStages stage);
class RenderPipelineState* newRenderPipelineState(const class RenderPipelineFunctionsDescriptor* additionalBinaryFunctions, NS::Error** error);
};
class RenderPipelineColorAttachmentDescriptorArray : public NS::Referencing<RenderPipelineColorAttachmentDescriptorArray>
{
public:
static class RenderPipelineColorAttachmentDescriptorArray* alloc();
class RenderPipelineColorAttachmentDescriptorArray* init();
class RenderPipelineColorAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class RenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class TileRenderPipelineColorAttachmentDescriptor : public NS::Copying<TileRenderPipelineColorAttachmentDescriptor>
{
public:
static class TileRenderPipelineColorAttachmentDescriptor* alloc();
class TileRenderPipelineColorAttachmentDescriptor* init();
MTL::PixelFormat pixelFormat() const;
void setPixelFormat(MTL::PixelFormat pixelFormat);
};
class TileRenderPipelineColorAttachmentDescriptorArray : public NS::Referencing<TileRenderPipelineColorAttachmentDescriptorArray>
{
public:
static class TileRenderPipelineColorAttachmentDescriptorArray* alloc();
class TileRenderPipelineColorAttachmentDescriptorArray* init();
class TileRenderPipelineColorAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class TileRenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class TileRenderPipelineDescriptor : public NS::Copying<TileRenderPipelineDescriptor>
{
public:
static class TileRenderPipelineDescriptor* alloc();
class TileRenderPipelineDescriptor* init();
NS::String* label() const;
void setLabel(const NS::String* label);
class Function* tileFunction() const;
void setTileFunction(const class Function* tileFunction);
NS::UInteger rasterSampleCount() const;
void setRasterSampleCount(NS::UInteger rasterSampleCount);
class TileRenderPipelineColorAttachmentDescriptorArray* colorAttachments() const;
bool threadgroupSizeMatchesTileSize() const;
void setThreadgroupSizeMatchesTileSize(bool threadgroupSizeMatchesTileSize);
class PipelineBufferDescriptorArray* tileBuffers() const;
NS::UInteger maxTotalThreadsPerThreadgroup() const;
void setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup);
NS::Array* binaryArchives() const;
void setBinaryArchives(const NS::Array* binaryArchives);
NS::Array* preloadedLibraries() const;
void setPreloadedLibraries(const NS::Array* preloadedLibraries);
class LinkedFunctions* linkedFunctions() const;
void setLinkedFunctions(const class LinkedFunctions* linkedFunctions);
bool supportAddingBinaryFunctions() const;
void setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions);
NS::UInteger maxCallStackDepth() const;
void setMaxCallStackDepth(NS::UInteger maxCallStackDepth);
void reset();
};
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPipelineColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineColorAttachmentDescriptor));
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptor::init()
{
return NS::Object::init<MTL::RenderPipelineColorAttachmentDescriptor>();
}
_MTL_INLINE MTL::PixelFormat MTL::RenderPipelineColorAttachmentDescriptor::pixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat);
}
_MTL_INLINE bool MTL::RenderPipelineColorAttachmentDescriptor::blendingEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isBlendingEnabled));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setBlendingEnabled(bool blendingEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBlendingEnabled_), blendingEnabled);
}
_MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::sourceRGBBlendFactor() const
{
return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(sourceRGBBlendFactor));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setSourceRGBBlendFactor(MTL::BlendFactor sourceRGBBlendFactor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSourceRGBBlendFactor_), sourceRGBBlendFactor);
}
_MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::destinationRGBBlendFactor() const
{
return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(destinationRGBBlendFactor));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setDestinationRGBBlendFactor(MTL::BlendFactor destinationRGBBlendFactor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestinationRGBBlendFactor_), destinationRGBBlendFactor);
}
_MTL_INLINE MTL::BlendOperation MTL::RenderPipelineColorAttachmentDescriptor::rgbBlendOperation() const
{
return Object::sendMessage<MTL::BlendOperation>(this, _MTL_PRIVATE_SEL(rgbBlendOperation));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setRgbBlendOperation(MTL::BlendOperation rgbBlendOperation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRgbBlendOperation_), rgbBlendOperation);
}
_MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::sourceAlphaBlendFactor() const
{
return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(sourceAlphaBlendFactor));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setSourceAlphaBlendFactor(MTL::BlendFactor sourceAlphaBlendFactor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSourceAlphaBlendFactor_), sourceAlphaBlendFactor);
}
_MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::destinationAlphaBlendFactor() const
{
return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(destinationAlphaBlendFactor));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setDestinationAlphaBlendFactor(MTL::BlendFactor destinationAlphaBlendFactor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestinationAlphaBlendFactor_), destinationAlphaBlendFactor);
}
_MTL_INLINE MTL::BlendOperation MTL::RenderPipelineColorAttachmentDescriptor::alphaBlendOperation() const
{
return Object::sendMessage<MTL::BlendOperation>(this, _MTL_PRIVATE_SEL(alphaBlendOperation));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setAlphaBlendOperation(MTL::BlendOperation alphaBlendOperation)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaBlendOperation_), alphaBlendOperation);
}
_MTL_INLINE MTL::ColorWriteMask MTL::RenderPipelineColorAttachmentDescriptor::writeMask() const
{
return Object::sendMessage<MTL::ColorWriteMask>(this, _MTL_PRIVATE_SEL(writeMask));
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setWriteMask(MTL::ColorWriteMask writeMask)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWriteMask_), writeMask);
}
_MTL_INLINE MTL::RenderPipelineReflection* MTL::RenderPipelineReflection::alloc()
{
return NS::Object::alloc<MTL::RenderPipelineReflection>(_MTL_PRIVATE_CLS(MTLRenderPipelineReflection));
}
_MTL_INLINE MTL::RenderPipelineReflection* MTL::RenderPipelineReflection::init()
{
return NS::Object::init<MTL::RenderPipelineReflection>();
}
_MTL_INLINE NS::Array* MTL::RenderPipelineReflection::vertexArguments() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexArguments));
}
_MTL_INLINE NS::Array* MTL::RenderPipelineReflection::fragmentArguments() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentArguments));
}
_MTL_INLINE NS::Array* MTL::RenderPipelineReflection::tileArguments() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(tileArguments));
}
_MTL_INLINE MTL::RenderPipelineDescriptor* MTL::RenderPipelineDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPipelineDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineDescriptor));
}
_MTL_INLINE MTL::RenderPipelineDescriptor* MTL::RenderPipelineDescriptor::init()
{
return NS::Object::init<MTL::RenderPipelineDescriptor>();
}
_MTL_INLINE NS::String* MTL::RenderPipelineDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Function* MTL::RenderPipelineDescriptor::vertexFunction() const
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(vertexFunction));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexFunction(const MTL::Function* vertexFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexFunction_), vertexFunction);
}
_MTL_INLINE MTL::Function* MTL::RenderPipelineDescriptor::fragmentFunction() const
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(fragmentFunction));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentFunction(const MTL::Function* fragmentFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentFunction_), fragmentFunction);
}
_MTL_INLINE MTL::VertexDescriptor* MTL::RenderPipelineDescriptor::vertexDescriptor() const
{
return Object::sendMessage<MTL::VertexDescriptor*>(this, _MTL_PRIVATE_SEL(vertexDescriptor));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexDescriptor(const MTL::VertexDescriptor* vertexDescriptor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexDescriptor_), vertexDescriptor);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::sampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setSampleCount(NS::UInteger sampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::rasterSampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(rasterSampleCount));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setRasterSampleCount(NS::UInteger rasterSampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterSampleCount_), rasterSampleCount);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::alphaToCoverageEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToCoverageEnabled));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setAlphaToCoverageEnabled(bool alphaToCoverageEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToCoverageEnabled_), alphaToCoverageEnabled);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::alphaToOneEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToOneEnabled));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setAlphaToOneEnabled(bool alphaToOneEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToOneEnabled_), alphaToOneEnabled);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::rasterizationEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isRasterizationEnabled));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setRasterizationEnabled(bool rasterizationEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterizationEnabled_), rasterizationEnabled);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxVertexAmplificationCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexAmplificationCount));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexAmplificationCount_), maxVertexAmplificationCount);
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineDescriptor::colorAttachments() const
{
return Object::sendMessage<MTL::RenderPipelineColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments));
}
_MTL_INLINE MTL::PixelFormat MTL::RenderPipelineDescriptor::depthAttachmentPixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(depthAttachmentPixelFormat));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthAttachmentPixelFormat_), depthAttachmentPixelFormat);
}
_MTL_INLINE MTL::PixelFormat MTL::RenderPipelineDescriptor::stencilAttachmentPixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(stencilAttachmentPixelFormat));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilAttachmentPixelFormat_), stencilAttachmentPixelFormat);
}
_MTL_INLINE MTL::PrimitiveTopologyClass MTL::RenderPipelineDescriptor::inputPrimitiveTopology() const
{
return Object::sendMessage<MTL::PrimitiveTopologyClass>(this, _MTL_PRIVATE_SEL(inputPrimitiveTopology));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setInputPrimitiveTopology(MTL::PrimitiveTopologyClass inputPrimitiveTopology)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInputPrimitiveTopology_), inputPrimitiveTopology);
}
_MTL_INLINE MTL::TessellationPartitionMode MTL::RenderPipelineDescriptor::tessellationPartitionMode() const
{
return Object::sendMessage<MTL::TessellationPartitionMode>(this, _MTL_PRIVATE_SEL(tessellationPartitionMode));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationPartitionMode(MTL::TessellationPartitionMode tessellationPartitionMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationPartitionMode_), tessellationPartitionMode);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxTessellationFactor() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTessellationFactor));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxTessellationFactor(NS::UInteger maxTessellationFactor)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTessellationFactor_), maxTessellationFactor);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::tessellationFactorScaleEnabled() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isTessellationFactorScaleEnabled));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorScaleEnabled(bool tessellationFactorScaleEnabled)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorScaleEnabled_), tessellationFactorScaleEnabled);
}
_MTL_INLINE MTL::TessellationFactorFormat MTL::RenderPipelineDescriptor::tessellationFactorFormat() const
{
return Object::sendMessage<MTL::TessellationFactorFormat>(this, _MTL_PRIVATE_SEL(tessellationFactorFormat));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorFormat(MTL::TessellationFactorFormat tessellationFactorFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorFormat_), tessellationFactorFormat);
}
_MTL_INLINE MTL::TessellationControlPointIndexType MTL::RenderPipelineDescriptor::tessellationControlPointIndexType() const
{
return Object::sendMessage<MTL::TessellationControlPointIndexType>(this, _MTL_PRIVATE_SEL(tessellationControlPointIndexType));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationControlPointIndexType(MTL::TessellationControlPointIndexType tessellationControlPointIndexType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationControlPointIndexType_), tessellationControlPointIndexType);
}
_MTL_INLINE MTL::TessellationFactorStepFunction MTL::RenderPipelineDescriptor::tessellationFactorStepFunction() const
{
return Object::sendMessage<MTL::TessellationFactorStepFunction>(this, _MTL_PRIVATE_SEL(tessellationFactorStepFunction));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorStepFunction(MTL::TessellationFactorStepFunction tessellationFactorStepFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorStepFunction_), tessellationFactorStepFunction);
}
_MTL_INLINE MTL::Winding MTL::RenderPipelineDescriptor::tessellationOutputWindingOrder() const
{
return Object::sendMessage<MTL::Winding>(this, _MTL_PRIVATE_SEL(tessellationOutputWindingOrder));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationOutputWindingOrder(MTL::Winding tessellationOutputWindingOrder)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationOutputWindingOrder_), tessellationOutputWindingOrder);
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::RenderPipelineDescriptor::vertexBuffers() const
{
return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(vertexBuffers));
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::RenderPipelineDescriptor::fragmentBuffers() const
{
return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(fragmentBuffers));
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::supportIndirectCommandBuffers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportIndirectCommandBuffers_), supportIndirectCommandBuffers);
}
_MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::binaryArchives() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives);
}
_MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::vertexPreloadedLibraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexPreloadedLibraries));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexPreloadedLibraries(const NS::Array* vertexPreloadedLibraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexPreloadedLibraries_), vertexPreloadedLibraries);
}
_MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::fragmentPreloadedLibraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentPreloadedLibraries));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentPreloadedLibraries(const NS::Array* fragmentPreloadedLibraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentPreloadedLibraries_), fragmentPreloadedLibraries);
}
_MTL_INLINE MTL::LinkedFunctions* MTL::RenderPipelineDescriptor::vertexLinkedFunctions() const
{
return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(vertexLinkedFunctions));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexLinkedFunctions(const MTL::LinkedFunctions* vertexLinkedFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexLinkedFunctions_), vertexLinkedFunctions);
}
_MTL_INLINE MTL::LinkedFunctions* MTL::RenderPipelineDescriptor::fragmentLinkedFunctions() const
{
return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(fragmentLinkedFunctions));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentLinkedFunctions(const MTL::LinkedFunctions* fragmentLinkedFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentLinkedFunctions_), fragmentLinkedFunctions);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::supportAddingVertexBinaryFunctions() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingVertexBinaryFunctions));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportAddingVertexBinaryFunctions(bool supportAddingVertexBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingVertexBinaryFunctions_), supportAddingVertexBinaryFunctions);
}
_MTL_INLINE bool MTL::RenderPipelineDescriptor::supportAddingFragmentBinaryFunctions() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingFragmentBinaryFunctions));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportAddingFragmentBinaryFunctions(bool supportAddingFragmentBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingFragmentBinaryFunctions_), supportAddingFragmentBinaryFunctions);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxVertexCallStackDepth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexCallStackDepth));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxVertexCallStackDepth(NS::UInteger maxVertexCallStackDepth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexCallStackDepth_), maxVertexCallStackDepth);
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxFragmentCallStackDepth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxFragmentCallStackDepth));
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxFragmentCallStackDepth(NS::UInteger maxFragmentCallStackDepth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxFragmentCallStackDepth_), maxFragmentCallStackDepth);
}
_MTL_INLINE void MTL::RenderPipelineDescriptor::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
_MTL_INLINE MTL::RenderPipelineFunctionsDescriptor* MTL::RenderPipelineFunctionsDescriptor::alloc()
{
return NS::Object::alloc<MTL::RenderPipelineFunctionsDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineFunctionsDescriptor));
}
_MTL_INLINE MTL::RenderPipelineFunctionsDescriptor* MTL::RenderPipelineFunctionsDescriptor::init()
{
return NS::Object::init<MTL::RenderPipelineFunctionsDescriptor>();
}
_MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::vertexAdditionalBinaryFunctions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexAdditionalBinaryFunctions));
}
_MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setVertexAdditionalBinaryFunctions(const NS::Array* vertexAdditionalBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAdditionalBinaryFunctions_), vertexAdditionalBinaryFunctions);
}
_MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::fragmentAdditionalBinaryFunctions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentAdditionalBinaryFunctions));
}
_MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setFragmentAdditionalBinaryFunctions(const NS::Array* fragmentAdditionalBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentAdditionalBinaryFunctions_), fragmentAdditionalBinaryFunctions);
}
_MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::tileAdditionalBinaryFunctions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(tileAdditionalBinaryFunctions));
}
_MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setTileAdditionalBinaryFunctions(const NS::Array* tileAdditionalBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileAdditionalBinaryFunctions_), tileAdditionalBinaryFunctions);
}
_MTL_INLINE NS::String* MTL::RenderPipelineState::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::Device* MTL::RenderPipelineState::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineState::maxTotalThreadsPerThreadgroup() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup));
}
_MTL_INLINE bool MTL::RenderPipelineState::threadgroupSizeMatchesTileSize() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadgroupSizeMatchesTileSize));
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineState::imageblockSampleLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockSampleLength));
}
_MTL_INLINE NS::UInteger MTL::RenderPipelineState::imageblockMemoryLength(MTL::Size imageblockDimensions)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockMemoryLengthForDimensions_), imageblockDimensions);
}
_MTL_INLINE bool MTL::RenderPipelineState::supportIndirectCommandBuffers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers));
}
_MTL_INLINE MTL::FunctionHandle* MTL::RenderPipelineState::functionHandle(const MTL::Function* function, MTL::RenderStages stage)
{
return Object::sendMessage<MTL::FunctionHandle*>(this, _MTL_PRIVATE_SEL(functionHandleWithFunction_stage_), function, stage);
}
_MTL_INLINE MTL::VisibleFunctionTable* MTL::RenderPipelineState::newVisibleFunctionTable(const MTL::VisibleFunctionTableDescriptor* descriptor, MTL::RenderStages stage)
{
return Object::sendMessage<MTL::VisibleFunctionTable*>(this, _MTL_PRIVATE_SEL(newVisibleFunctionTableWithDescriptor_stage_), descriptor, stage);
}
_MTL_INLINE MTL::IntersectionFunctionTable* MTL::RenderPipelineState::newIntersectionFunctionTable(const MTL::IntersectionFunctionTableDescriptor* descriptor, MTL::RenderStages stage)
{
return Object::sendMessage<MTL::IntersectionFunctionTable*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionTableWithDescriptor_stage_), descriptor, stage);
}
_MTL_INLINE MTL::RenderPipelineState* MTL::RenderPipelineState::newRenderPipelineState(const MTL::RenderPipelineFunctionsDescriptor* additionalBinaryFunctions, NS::Error** error)
{
return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithAdditionalBinaryFunctions_error_), additionalBinaryFunctions, error);
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineColorAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::RenderPipelineColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPipelineColorAttachmentDescriptorArray));
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineColorAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::RenderPipelineColorAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::RenderPipelineColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptorArray::setObject(const MTL::RenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::TileRenderPipelineColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineColorAttachmentDescriptor));
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptor::init()
{
return NS::Object::init<MTL::TileRenderPipelineColorAttachmentDescriptor>();
}
_MTL_INLINE MTL::PixelFormat MTL::TileRenderPipelineColorAttachmentDescriptor::pixelFormat() const
{
return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat));
}
_MTL_INLINE void MTL::TileRenderPipelineColorAttachmentDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat);
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineColorAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::TileRenderPipelineColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineColorAttachmentDescriptorArray));
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineColorAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::TileRenderPipelineColorAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::TileRenderPipelineColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::TileRenderPipelineColorAttachmentDescriptorArray::setObject(const MTL::TileRenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::TileRenderPipelineDescriptor* MTL::TileRenderPipelineDescriptor::alloc()
{
return NS::Object::alloc<MTL::TileRenderPipelineDescriptor>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineDescriptor));
}
_MTL_INLINE MTL::TileRenderPipelineDescriptor* MTL::TileRenderPipelineDescriptor::init()
{
return NS::Object::init<MTL::TileRenderPipelineDescriptor>();
}
_MTL_INLINE NS::String* MTL::TileRenderPipelineDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Function* MTL::TileRenderPipelineDescriptor::tileFunction() const
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(tileFunction));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setTileFunction(const MTL::Function* tileFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileFunction_), tileFunction);
}
_MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::rasterSampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(rasterSampleCount));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setRasterSampleCount(NS::UInteger rasterSampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterSampleCount_), rasterSampleCount);
}
_MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineDescriptor::colorAttachments() const
{
return Object::sendMessage<MTL::TileRenderPipelineColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments));
}
_MTL_INLINE bool MTL::TileRenderPipelineDescriptor::threadgroupSizeMatchesTileSize() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadgroupSizeMatchesTileSize));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setThreadgroupSizeMatchesTileSize(bool threadgroupSizeMatchesTileSize)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupSizeMatchesTileSize_), threadgroupSizeMatchesTileSize);
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::TileRenderPipelineDescriptor::tileBuffers() const
{
return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(tileBuffers));
}
_MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::maxTotalThreadsPerThreadgroup() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerThreadgroup_), maxTotalThreadsPerThreadgroup);
}
_MTL_INLINE NS::Array* MTL::TileRenderPipelineDescriptor::binaryArchives() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives);
}
_MTL_INLINE NS::Array* MTL::TileRenderPipelineDescriptor::preloadedLibraries() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(preloadedLibraries));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setPreloadedLibraries(const NS::Array* preloadedLibraries)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreloadedLibraries_), preloadedLibraries);
}
_MTL_INLINE MTL::LinkedFunctions* MTL::TileRenderPipelineDescriptor::linkedFunctions() const
{
return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(linkedFunctions));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setLinkedFunctions(const MTL::LinkedFunctions* linkedFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLinkedFunctions_), linkedFunctions);
}
_MTL_INLINE bool MTL::TileRenderPipelineDescriptor::supportAddingBinaryFunctions() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingBinaryFunctions));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingBinaryFunctions_), supportAddingBinaryFunctions);
}
_MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::maxCallStackDepth() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCallStackDepth));
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::setMaxCallStackDepth(NS::UInteger maxCallStackDepth)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCallStackDepth_), maxCallStackDepth);
}
_MTL_INLINE void MTL::TileRenderPipelineDescriptor::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
namespace MTL
{
class ArgumentEncoder : public NS::Referencing<ArgumentEncoder>
{
public:
class Device* device() const;
NS::String* label() const;
void setLabel(const NS::String* label);
NS::UInteger encodedLength() const;
NS::UInteger alignment() const;
void setArgumentBuffer(const class Buffer* argumentBuffer, NS::UInteger offset);
void setArgumentBuffer(const class Buffer* argumentBuffer, NS::UInteger startOffset, NS::UInteger arrayElement);
void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range);
void setTexture(const class Texture* texture, NS::UInteger index);
void setTextures(MTL::Texture* textures[], NS::Range range);
void setSamplerState(const class SamplerState* sampler, NS::UInteger index);
void setSamplerStates(MTL::SamplerState* samplers[], NS::Range range);
void* constantData(NS::UInteger index);
void setRenderPipelineState(const class RenderPipelineState* pipeline, NS::UInteger index);
void setRenderPipelineStates(MTL::RenderPipelineState* pipelines, NS::Range range);
void setComputePipelineState(const class ComputePipelineState* pipeline, NS::UInteger index);
void setComputePipelineStates(MTL::ComputePipelineState* pipelines, NS::Range range);
void setIndirectCommandBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::UInteger index);
void setIndirectCommandBuffers(MTL::IndirectCommandBuffer* buffers, NS::Range range);
void setAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger index);
class ArgumentEncoder* newArgumentEncoder(NS::UInteger index);
void setVisibleFunctionTable(const class VisibleFunctionTable* visibleFunctionTable, NS::UInteger index);
void setVisibleFunctionTables(const VisibleFunctionTable* visibleFunctionTables[], NS::Range range);
void setIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger index);
void setIntersectionFunctionTables(const IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range);
};
}
_MTL_INLINE MTL::Device* MTL::ArgumentEncoder::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::ArgumentEncoder::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::ArgumentEncoder::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE NS::UInteger MTL::ArgumentEncoder::encodedLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(encodedLength));
}
_MTL_INLINE NS::UInteger MTL::ArgumentEncoder::alignment() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(alignment));
}
_MTL_INLINE void MTL::ArgumentEncoder::setArgumentBuffer(const MTL::Buffer* argumentBuffer, NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentBuffer_offset_), argumentBuffer, offset);
}
_MTL_INLINE void MTL::ArgumentEncoder::setArgumentBuffer(const MTL::Buffer* argumentBuffer, NS::UInteger startOffset, NS::UInteger arrayElement)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentBuffer_startOffset_arrayElement_), argumentBuffer, startOffset, arrayElement);
}
_MTL_INLINE void MTL::ArgumentEncoder::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setTexture(const MTL::Texture* texture, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_atIndex_), texture, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setTextures(MTL::Texture* textures[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextures_withRange_), textures, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setSamplerState(const MTL::SamplerState* sampler, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_atIndex_), sampler, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setSamplerStates(MTL::SamplerState* samplers[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_withRange_), samplers, range);
}
_MTL_INLINE void* MTL::ArgumentEncoder::constantData(NS::UInteger index)
{
return Object::sendMessage<void*>(this, _MTL_PRIVATE_SEL(constantDataAtIndex_), index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setRenderPipelineState(const MTL::RenderPipelineState* pipeline, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_atIndex_), pipeline, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setRenderPipelineStates(MTL::RenderPipelineState* pipelines, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineStates_withRange_), pipelines, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setComputePipelineState(const MTL::ComputePipelineState* pipeline, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_atIndex_), pipeline, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setComputePipelineStates(MTL::ComputePipelineState* pipelines, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineStates_withRange_), pipelines, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setIndirectCommandBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndirectCommandBuffer_atIndex_), indirectCommandBuffer, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setIndirectCommandBuffers(MTL::IndirectCommandBuffer* buffers, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndirectCommandBuffers_withRange_), buffers, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccelerationStructure_atIndex_), accelerationStructure, index);
}
_MTL_INLINE MTL::ArgumentEncoder* MTL::ArgumentEncoder::newArgumentEncoder(NS::UInteger index)
{
return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderForBufferAtIndex_), index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setVisibleFunctionTable(const MTL::VisibleFunctionTable* visibleFunctionTable, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atIndex_), visibleFunctionTable, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setVisibleFunctionTables(const MTL::VisibleFunctionTable* visibleFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withRange_), visibleFunctionTables, range);
}
_MTL_INLINE void MTL::ArgumentEncoder::setIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTable_atIndex_), intersectionFunctionTable, index);
}
_MTL_INLINE void MTL::ArgumentEncoder::setIntersectionFunctionTables(const MTL::IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTables_withRange_), intersectionFunctionTables, range);
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, BinaryArchiveError) {
BinaryArchiveErrorNone = 0,
BinaryArchiveErrorInvalidFile = 1,
BinaryArchiveErrorUnexpectedElement = 2,
BinaryArchiveErrorCompilationFailure = 3,
};
class BinaryArchiveDescriptor : public NS::Copying<BinaryArchiveDescriptor>
{
public:
static class BinaryArchiveDescriptor* alloc();
class BinaryArchiveDescriptor* init();
NS::URL* url() const;
void setUrl(const NS::URL* url);
};
class BinaryArchive : public NS::Referencing<BinaryArchive>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
bool addComputePipelineFunctions(const class ComputePipelineDescriptor* descriptor, NS::Error** error);
bool addRenderPipelineFunctions(const class RenderPipelineDescriptor* descriptor, NS::Error** error);
bool addTileRenderPipelineFunctions(const class TileRenderPipelineDescriptor* descriptor, NS::Error** error);
bool serializeToURL(const NS::URL* url, NS::Error** error);
bool addFunction(const class FunctionDescriptor* descriptor, const class Library* library, NS::Error** error);
};
}
_MTL_INLINE MTL::BinaryArchiveDescriptor* MTL::BinaryArchiveDescriptor::alloc()
{
return NS::Object::alloc<MTL::BinaryArchiveDescriptor>(_MTL_PRIVATE_CLS(MTLBinaryArchiveDescriptor));
}
_MTL_INLINE MTL::BinaryArchiveDescriptor* MTL::BinaryArchiveDescriptor::init()
{
return NS::Object::init<MTL::BinaryArchiveDescriptor>();
}
_MTL_INLINE NS::URL* MTL::BinaryArchiveDescriptor::url() const
{
return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(url));
}
_MTL_INLINE void MTL::BinaryArchiveDescriptor::setUrl(const NS::URL* url)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUrl_), url);
}
_MTL_INLINE NS::String* MTL::BinaryArchive::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::BinaryArchive::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::BinaryArchive::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE bool MTL::BinaryArchive::addComputePipelineFunctions(const MTL::ComputePipelineDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addComputePipelineFunctionsWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE bool MTL::BinaryArchive::addRenderPipelineFunctions(const MTL::RenderPipelineDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addRenderPipelineFunctionsWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE bool MTL::BinaryArchive::addTileRenderPipelineFunctions(const MTL::TileRenderPipelineDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addTileRenderPipelineFunctionsWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE bool MTL::BinaryArchive::serializeToURL(const NS::URL* url, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(serializeToURL_error_), url, error);
}
_MTL_INLINE bool MTL::BinaryArchive::addFunction(const MTL::FunctionDescriptor* descriptor, const MTL::Library* library, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addFunctionWithDescriptor_library_error_), descriptor, library, error);
}
#pragma once
namespace MTL
{
_MTL_OPTIONS(NS::UInteger, BlitOption) {
BlitOptionNone = 0,
BlitOptionDepthFromDepthStencil = 1,
BlitOptionStencilFromDepthStencil = 2,
BlitOptionRowLinearPVRTC = 4,
};
class BlitCommandEncoder : public NS::Referencing<BlitCommandEncoder, CommandEncoder>
{
public:
void synchronizeResource(const class Resource* resource);
void synchronizeTexture(const class Texture* texture, NS::UInteger slice, NS::UInteger level);
void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin);
void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin);
void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin, MTL::BlitOption options);
void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage);
void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage, MTL::BlitOption options);
void generateMipmaps(const class Texture* texture);
void fillBuffer(const class Buffer* buffer, NS::Range range, uint8_t value);
void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, NS::UInteger sliceCount, NS::UInteger levelCount);
void copyFromTexture(const class Texture* sourceTexture, const class Texture* destinationTexture);
void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger size);
void updateFence(const class Fence* fence);
void waitForFence(const class Fence* fence);
void getTextureAccessCounters(const class Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice, bool resetCounters, const class Buffer* countersBuffer, NS::UInteger countersBufferOffset);
void resetTextureAccessCounters(const class Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice);
void optimizeContentsForGPUAccess(const class Texture* texture);
void optimizeContentsForGPUAccess(const class Texture* texture, NS::UInteger slice, NS::UInteger level);
void optimizeContentsForCPUAccess(const class Texture* texture);
void optimizeContentsForCPUAccess(const class Texture* texture, NS::UInteger slice, NS::UInteger level);
void resetCommandsInBuffer(const class IndirectCommandBuffer* buffer, NS::Range range);
void copyIndirectCommandBuffer(const class IndirectCommandBuffer* source, NS::Range sourceRange, const class IndirectCommandBuffer* destination, NS::UInteger destinationIndex);
void optimizeIndirectCommandBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range range);
void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier);
void resolveCounters(const class CounterSampleBuffer* sampleBuffer, NS::Range range, const class Buffer* destinationBuffer, NS::UInteger destinationOffset);
};
}
_MTL_INLINE void MTL::BlitCommandEncoder::synchronizeResource(const MTL::Resource* resource)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(synchronizeResource_), resource);
}
_MTL_INLINE void MTL::BlitCommandEncoder::synchronizeTexture(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(synchronizeTexture_slice_level_), texture, slice, level);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_), sourceBuffer, sourceOffset, sourceBytesPerRow, sourceBytesPerImage, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin, MTL::BlitOption options)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options_), sourceBuffer, sourceOffset, sourceBytesPerRow, sourceBytesPerImage, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin, options);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationBuffer, destinationOffset, destinationBytesPerRow, destinationBytesPerImage);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage, MTL::BlitOption options)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationBuffer, destinationOffset, destinationBytesPerRow, destinationBytesPerImage, options);
}
_MTL_INLINE void MTL::BlitCommandEncoder::generateMipmaps(const MTL::Texture* texture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(generateMipmapsForTexture_), texture);
}
_MTL_INLINE void MTL::BlitCommandEncoder::fillBuffer(const MTL::Buffer* buffer, NS::Range range, uint8_t value)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(fillBuffer_range_value_), buffer, range, value);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, NS::UInteger sliceCount, NS::UInteger levelCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_toTexture_destinationSlice_destinationLevel_sliceCount_levelCount_), sourceTexture, sourceSlice, sourceLevel, destinationTexture, destinationSlice, destinationLevel, sliceCount, levelCount);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, const MTL::Texture* destinationTexture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_toTexture_), sourceTexture, destinationTexture);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger size)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size_), sourceBuffer, sourceOffset, destinationBuffer, destinationOffset, size);
}
_MTL_INLINE void MTL::BlitCommandEncoder::updateFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence);
}
_MTL_INLINE void MTL::BlitCommandEncoder::waitForFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence);
}
_MTL_INLINE void MTL::BlitCommandEncoder::getTextureAccessCounters(const MTL::Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice, bool resetCounters, const MTL::Buffer* countersBuffer, NS::UInteger countersBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getTextureAccessCounters_region_mipLevel_slice_resetCounters_countersBuffer_countersBufferOffset_), texture, region, mipLevel, slice, resetCounters, countersBuffer, countersBufferOffset);
}
_MTL_INLINE void MTL::BlitCommandEncoder::resetTextureAccessCounters(const MTL::Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetTextureAccessCounters_region_mipLevel_slice_), texture, region, mipLevel, slice);
}
_MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForGPUAccess(const MTL::Texture* texture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForGPUAccess_), texture);
}
_MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForGPUAccess(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForGPUAccess_slice_level_), texture, slice, level);
}
_MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForCPUAccess(const MTL::Texture* texture)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForCPUAccess_), texture);
}
_MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForCPUAccess(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForCPUAccess_slice_level_), texture, slice, level);
}
_MTL_INLINE void MTL::BlitCommandEncoder::resetCommandsInBuffer(const MTL::IndirectCommandBuffer* buffer, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetCommandsInBuffer_withRange_), buffer, range);
}
_MTL_INLINE void MTL::BlitCommandEncoder::copyIndirectCommandBuffer(const MTL::IndirectCommandBuffer* source, NS::Range sourceRange, const MTL::IndirectCommandBuffer* destination, NS::UInteger destinationIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyIndirectCommandBuffer_sourceRange_destination_destinationIndex_), source, sourceRange, destination, destinationIndex);
}
_MTL_INLINE void MTL::BlitCommandEncoder::optimizeIndirectCommandBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeIndirectCommandBuffer_withRange_), indirectCommandBuffer, range);
}
_MTL_INLINE void MTL::BlitCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier);
}
_MTL_INLINE void MTL::BlitCommandEncoder::resolveCounters(const MTL::CounterSampleBuffer* sampleBuffer, NS::Range range, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resolveCounters_inRange_destinationBuffer_destinationOffset_), sampleBuffer, range, destinationBuffer, destinationOffset);
}
#pragma once
namespace MTL
{
class BlitPassSampleBufferAttachmentDescriptor : public NS::Copying<BlitPassSampleBufferAttachmentDescriptor>
{
public:
static class BlitPassSampleBufferAttachmentDescriptor* alloc();
class BlitPassSampleBufferAttachmentDescriptor* init();
class CounterSampleBuffer* sampleBuffer() const;
void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer);
NS::UInteger startOfEncoderSampleIndex() const;
void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex);
NS::UInteger endOfEncoderSampleIndex() const;
void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex);
};
class BlitPassSampleBufferAttachmentDescriptorArray : public NS::Referencing<BlitPassSampleBufferAttachmentDescriptorArray>
{
public:
static class BlitPassSampleBufferAttachmentDescriptorArray* alloc();
class BlitPassSampleBufferAttachmentDescriptorArray* init();
class BlitPassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class BlitPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class BlitPassDescriptor : public NS::Copying<BlitPassDescriptor>
{
public:
static class BlitPassDescriptor* alloc();
class BlitPassDescriptor* init();
static class BlitPassDescriptor* blitPassDescriptor();
class BlitPassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const;
};
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::BlitPassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLBlitPassSampleBufferAttachmentDescriptor));
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptor::init()
{
return NS::Object::init<MTL::BlitPassSampleBufferAttachmentDescriptor>();
}
_MTL_INLINE MTL::CounterSampleBuffer* MTL::BlitPassSampleBufferAttachmentDescriptor::sampleBuffer() const
{
return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer));
}
_MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer);
}
_MTL_INLINE NS::UInteger MTL::BlitPassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::BlitPassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex);
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassSampleBufferAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::BlitPassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLBlitPassSampleBufferAttachmentDescriptorArray));
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassSampleBufferAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::BlitPassSampleBufferAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::BlitPassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptorArray::setObject(const MTL::BlitPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::alloc()
{
return NS::Object::alloc<MTL::BlitPassDescriptor>(_MTL_PRIVATE_CLS(MTLBlitPassDescriptor));
}
_MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::init()
{
return NS::Object::init<MTL::BlitPassDescriptor>();
}
_MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::blitPassDescriptor()
{
return Object::sendMessage<MTL::BlitPassDescriptor*>(_MTL_PRIVATE_CLS(MTLBlitPassDescriptor), _MTL_PRIVATE_SEL(blitPassDescriptor));
}
_MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassDescriptor::sampleBufferAttachments() const
{
return Object::sendMessage<MTL::BlitPassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments));
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::Integer, CaptureError) {
CaptureErrorNotSupported = 1,
CaptureErrorAlreadyCapturing = 2,
CaptureErrorInvalidDescriptor = 3,
};
_MTL_ENUM(NS::Integer, CaptureDestination) {
CaptureDestinationDeveloperTools = 1,
CaptureDestinationGPUTraceDocument = 2,
};
class CaptureDescriptor : public NS::Copying<CaptureDescriptor>
{
public:
static class CaptureDescriptor* alloc();
class CaptureDescriptor* init();
id captureObject() const;
void setCaptureObject(id captureObject);
MTL::CaptureDestination destination() const;
void setDestination(MTL::CaptureDestination destination);
NS::URL* outputURL() const;
void setOutputURL(const NS::URL* outputURL);
};
class CaptureManager : public NS::Referencing<CaptureManager>
{
public:
static class CaptureManager* alloc();
static class CaptureManager* sharedCaptureManager();
MTL::CaptureManager* init();
class CaptureScope* newCaptureScope(const class Device* device);
class CaptureScope* newCaptureScope(const class CommandQueue* commandQueue);
bool supportsDestination(MTL::CaptureDestination destination);
bool startCapture(const class CaptureDescriptor* descriptor, NS::Error** error);
void startCapture(const class Device* device);
void startCapture(const class CommandQueue* commandQueue);
void startCapture(const class CaptureScope* captureScope);
void stopCapture();
class CaptureScope* defaultCaptureScope() const;
void setDefaultCaptureScope(const class CaptureScope* defaultCaptureScope);
bool isCapturing() const;
};
}
_MTL_INLINE MTL::CaptureDescriptor* MTL::CaptureDescriptor::alloc()
{
return NS::Object::alloc<MTL::CaptureDescriptor>(_MTL_PRIVATE_CLS(MTLCaptureDescriptor));
}
_MTL_INLINE MTL::CaptureDescriptor* MTL::CaptureDescriptor::init()
{
return NS::Object::init<MTL::CaptureDescriptor>();
}
_MTL_INLINE id MTL::CaptureDescriptor::captureObject() const
{
return Object::sendMessage<id>(this, _MTL_PRIVATE_SEL(captureObject));
}
_MTL_INLINE void MTL::CaptureDescriptor::setCaptureObject(id captureObject)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCaptureObject_), captureObject);
}
_MTL_INLINE MTL::CaptureDestination MTL::CaptureDescriptor::destination() const
{
return Object::sendMessage<MTL::CaptureDestination>(this, _MTL_PRIVATE_SEL(destination));
}
_MTL_INLINE void MTL::CaptureDescriptor::setDestination(MTL::CaptureDestination destination)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestination_), destination);
}
_MTL_INLINE NS::URL* MTL::CaptureDescriptor::outputURL() const
{
return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(outputURL));
}
_MTL_INLINE void MTL::CaptureDescriptor::setOutputURL(const NS::URL* outputURL)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOutputURL_), outputURL);
}
_MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::alloc()
{
return NS::Object::alloc<MTL::CaptureManager>(_MTL_PRIVATE_CLS(MTLCaptureManager));
}
_MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::sharedCaptureManager()
{
return Object::sendMessage<MTL::CaptureManager*>(_MTL_PRIVATE_CLS(MTLCaptureManager), _MTL_PRIVATE_SEL(sharedCaptureManager));
}
_MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::init()
{
return NS::Object::init<MTL::CaptureManager>();
}
_MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::newCaptureScope(const MTL::Device* device)
{
return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(newCaptureScopeWithDevice_), device);
}
_MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::newCaptureScope(const MTL::CommandQueue* commandQueue)
{
return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(newCaptureScopeWithCommandQueue_), commandQueue);
}
_MTL_INLINE bool MTL::CaptureManager::supportsDestination(MTL::CaptureDestination destination)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsDestination_), destination);
}
_MTL_INLINE bool MTL::CaptureManager::startCapture(const MTL::CaptureDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(startCaptureWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::Device* device)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithDevice_), device);
}
_MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::CommandQueue* commandQueue)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithCommandQueue_), commandQueue);
}
_MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::CaptureScope* captureScope)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithScope_), captureScope);
}
_MTL_INLINE void MTL::CaptureManager::stopCapture()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(stopCapture));
}
_MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::defaultCaptureScope() const
{
return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(defaultCaptureScope));
}
_MTL_INLINE void MTL::CaptureManager::setDefaultCaptureScope(const MTL::CaptureScope* defaultCaptureScope)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDefaultCaptureScope_), defaultCaptureScope);
}
_MTL_INLINE bool MTL::CaptureManager::isCapturing() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isCapturing));
}
namespace MTL
{
class CaptureScope : public NS::Referencing<CaptureScope>
{
public:
class Device* device() const;
NS::String* label() const;
void setLabel(const NS::String* pLabel);
class CommandQueue* commandQueue() const;
void beginScope();
void endScope();
};
}
_MTL_INLINE MTL::Device* MTL::CaptureScope::device() const
{
return Object::sendMessage<Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::CaptureScope::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::CaptureScope::setLabel(const NS::String* pLabel)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), pLabel);
}
_MTL_INLINE MTL::CommandQueue* MTL::CaptureScope::commandQueue() const
{
return Object::sendMessage<CommandQueue*>(this, _MTL_PRIVATE_SEL(commandQueue));
}
_MTL_INLINE void MTL::CaptureScope::beginScope()
{
return Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(beginScope));
}
_MTL_INLINE void MTL::CaptureScope::endScope()
{
return Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(endScope));
}
#pragma once
#include <functional>
namespace MTL
{
_MTL_ENUM(NS::UInteger, CommandBufferStatus) {
CommandBufferStatusNotEnqueued = 0,
CommandBufferStatusEnqueued = 1,
CommandBufferStatusCommitted = 2,
CommandBufferStatusScheduled = 3,
CommandBufferStatusCompleted = 4,
CommandBufferStatusError = 5,
};
_MTL_ENUM(NS::UInteger, CommandBufferError) {
CommandBufferErrorNone = 0,
CommandBufferErrorTimeout = 2,
CommandBufferErrorPageFault = 3,
CommandBufferErrorAccessRevoked = 4,
CommandBufferErrorBlacklisted = 4,
CommandBufferErrorNotPermitted = 7,
CommandBufferErrorOutOfMemory = 8,
CommandBufferErrorInvalidResource = 9,
CommandBufferErrorMemoryless = 10,
CommandBufferErrorDeviceRemoved = 11,
CommandBufferErrorStackOverflow = 12,
};
_MTL_OPTIONS(NS::UInteger, CommandBufferErrorOption) {
CommandBufferErrorOptionNone = 0,
CommandBufferErrorOptionEncoderExecutionStatus = 1,
};
_MTL_ENUM(NS::Integer, CommandEncoderErrorState) {
CommandEncoderErrorStateUnknown = 0,
CommandEncoderErrorStateCompleted = 1,
CommandEncoderErrorStateAffected = 2,
CommandEncoderErrorStatePending = 3,
CommandEncoderErrorStateFaulted = 4,
};
class CommandBufferDescriptor : public NS::Copying<CommandBufferDescriptor>
{
public:
static class CommandBufferDescriptor* alloc();
class CommandBufferDescriptor* init();
bool retainedReferences() const;
void setRetainedReferences(bool retainedReferences);
MTL::CommandBufferErrorOption errorOptions() const;
void setErrorOptions(MTL::CommandBufferErrorOption errorOptions);
};
class CommandBufferEncoderInfo : public NS::Referencing<CommandBufferEncoderInfo>
{
public:
NS::String* label() const;
NS::Array* debugSignposts() const;
MTL::CommandEncoderErrorState errorState() const;
};
_MTL_ENUM(NS::UInteger, DispatchType) {
DispatchTypeSerial = 0,
DispatchTypeConcurrent = 1,
};
class CommandBuffer;
using CommandBufferHandler = void (^)(CommandBuffer*);
using HandlerFunction = std::function<void(CommandBuffer*)>;
class CommandBuffer : public NS::Referencing<CommandBuffer>
{
public:
void addScheduledHandler(const HandlerFunction& function);
void addCompletedHandler(const HandlerFunction& function);
class Device* device() const;
class CommandQueue* commandQueue() const;
bool retainedReferences() const;
MTL::CommandBufferErrorOption errorOptions() const;
NS::String* label() const;
void setLabel(const NS::String* label);
CFTimeInterval kernelStartTime() const;
CFTimeInterval kernelEndTime() const;
class LogContainer* logs() const;
CFTimeInterval GPUStartTime() const;
CFTimeInterval GPUEndTime() const;
void enqueue();
void commit();
void addScheduledHandler(const MTL::CommandBufferHandler block);
void presentDrawable(const class Drawable* drawable);
void presentDrawableAtTime(const class Drawable* drawable, CFTimeInterval presentationTime);
void presentDrawableAfterMinimumDuration(const class Drawable* drawable, CFTimeInterval duration);
void waitUntilScheduled();
void addCompletedHandler(const MTL::CommandBufferHandler block);
void waitUntilCompleted();
MTL::CommandBufferStatus status() const;
NS::Error* error() const;
class BlitCommandEncoder* blitCommandEncoder();
class RenderCommandEncoder* renderCommandEncoder(const class RenderPassDescriptor* renderPassDescriptor);
class ComputeCommandEncoder* computeCommandEncoder(const class ComputePassDescriptor* computePassDescriptor);
class BlitCommandEncoder* blitCommandEncoder(const class BlitPassDescriptor* blitPassDescriptor);
class ComputeCommandEncoder* computeCommandEncoder();
class ComputeCommandEncoder* computeCommandEncoder(MTL::DispatchType dispatchType);
void encodeWait(const class Event* event, uint64_t value);
void encodeSignalEvent(const class Event* event, uint64_t value);
class ParallelRenderCommandEncoder* parallelRenderCommandEncoder(const class RenderPassDescriptor* renderPassDescriptor);
class ResourceStateCommandEncoder* resourceStateCommandEncoder();
class ResourceStateCommandEncoder* resourceStateCommandEncoder(const class ResourceStatePassDescriptor* resourceStatePassDescriptor);
class AccelerationStructureCommandEncoder* accelerationStructureCommandEncoder();
void pushDebugGroup(const NS::String* string);
void popDebugGroup();
};
}
_MTL_INLINE MTL::CommandBufferDescriptor* MTL::CommandBufferDescriptor::alloc()
{
return NS::Object::alloc<MTL::CommandBufferDescriptor>(_MTL_PRIVATE_CLS(MTLCommandBufferDescriptor));
}
_MTL_INLINE MTL::CommandBufferDescriptor* MTL::CommandBufferDescriptor::init()
{
return NS::Object::init<MTL::CommandBufferDescriptor>();
}
_MTL_INLINE bool MTL::CommandBufferDescriptor::retainedReferences() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(retainedReferences));
}
_MTL_INLINE void MTL::CommandBufferDescriptor::setRetainedReferences(bool retainedReferences)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRetainedReferences_), retainedReferences);
}
_MTL_INLINE MTL::CommandBufferErrorOption MTL::CommandBufferDescriptor::errorOptions() const
{
return Object::sendMessage<MTL::CommandBufferErrorOption>(this, _MTL_PRIVATE_SEL(errorOptions));
}
_MTL_INLINE void MTL::CommandBufferDescriptor::setErrorOptions(MTL::CommandBufferErrorOption errorOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setErrorOptions_), errorOptions);
}
_MTL_INLINE NS::String* MTL::CommandBufferEncoderInfo::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE NS::Array* MTL::CommandBufferEncoderInfo::debugSignposts() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(debugSignposts));
}
_MTL_INLINE MTL::CommandEncoderErrorState MTL::CommandBufferEncoderInfo::errorState() const
{
return Object::sendMessage<MTL::CommandEncoderErrorState>(this, _MTL_PRIVATE_SEL(errorState));
}
_MTL_INLINE void MTL::CommandBuffer::addScheduledHandler(const HandlerFunction& function)
{
__block HandlerFunction blockFunction = function;
addScheduledHandler(^(MTL::CommandBuffer* pCommandBuffer) { blockFunction(pCommandBuffer); });
}
_MTL_INLINE void MTL::CommandBuffer::addCompletedHandler(const HandlerFunction& function)
{
__block HandlerFunction blockFunction = function;
addCompletedHandler(^(MTL::CommandBuffer* pCommandBuffer) { blockFunction(pCommandBuffer); });
}
_MTL_INLINE MTL::Device* MTL::CommandBuffer::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::CommandQueue* MTL::CommandBuffer::commandQueue() const
{
return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(commandQueue));
}
_MTL_INLINE bool MTL::CommandBuffer::retainedReferences() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(retainedReferences));
}
_MTL_INLINE MTL::CommandBufferErrorOption MTL::CommandBuffer::errorOptions() const
{
return Object::sendMessage<MTL::CommandBufferErrorOption>(this, _MTL_PRIVATE_SEL(errorOptions));
}
_MTL_INLINE NS::String* MTL::CommandBuffer::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::CommandBuffer::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE CFTimeInterval MTL::CommandBuffer::kernelStartTime() const
{
return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(kernelStartTime));
}
_MTL_INLINE CFTimeInterval MTL::CommandBuffer::kernelEndTime() const
{
return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(kernelEndTime));
}
_MTL_INLINE MTL::LogContainer* MTL::CommandBuffer::logs() const
{
return Object::sendMessage<MTL::LogContainer*>(this, _MTL_PRIVATE_SEL(logs));
}
_MTL_INLINE CFTimeInterval MTL::CommandBuffer::GPUStartTime() const
{
return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(GPUStartTime));
}
_MTL_INLINE CFTimeInterval MTL::CommandBuffer::GPUEndTime() const
{
return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(GPUEndTime));
}
_MTL_INLINE void MTL::CommandBuffer::enqueue()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(enqueue));
}
_MTL_INLINE void MTL::CommandBuffer::commit()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(commit));
}
_MTL_INLINE void MTL::CommandBuffer::addScheduledHandler(const MTL::CommandBufferHandler block)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addScheduledHandler_), block);
}
_MTL_INLINE void MTL::CommandBuffer::presentDrawable(const MTL::Drawable* drawable)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_), drawable);
}
_MTL_INLINE void MTL::CommandBuffer::presentDrawableAtTime(const MTL::Drawable* drawable, CFTimeInterval presentationTime)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_atTime_), drawable, presentationTime);
}
_MTL_INLINE void MTL::CommandBuffer::presentDrawableAfterMinimumDuration(const MTL::Drawable* drawable, CFTimeInterval duration)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_afterMinimumDuration_), drawable, duration);
}
_MTL_INLINE void MTL::CommandBuffer::waitUntilScheduled()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitUntilScheduled));
}
_MTL_INLINE void MTL::CommandBuffer::addCompletedHandler(const MTL::CommandBufferHandler block)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addCompletedHandler_), block);
}
_MTL_INLINE void MTL::CommandBuffer::waitUntilCompleted()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitUntilCompleted));
}
_MTL_INLINE MTL::CommandBufferStatus MTL::CommandBuffer::status() const
{
return Object::sendMessage<MTL::CommandBufferStatus>(this, _MTL_PRIVATE_SEL(status));
}
_MTL_INLINE NS::Error* MTL::CommandBuffer::error() const
{
return Object::sendMessage<NS::Error*>(this, _MTL_PRIVATE_SEL(error));
}
_MTL_INLINE MTL::BlitCommandEncoder* MTL::CommandBuffer::blitCommandEncoder()
{
return Object::sendMessage<MTL::BlitCommandEncoder*>(this, _MTL_PRIVATE_SEL(blitCommandEncoder));
}
_MTL_INLINE MTL::RenderCommandEncoder* MTL::CommandBuffer::renderCommandEncoder(const MTL::RenderPassDescriptor* renderPassDescriptor)
{
return Object::sendMessage<MTL::RenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(renderCommandEncoderWithDescriptor_), renderPassDescriptor);
}
_MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder(const MTL::ComputePassDescriptor* computePassDescriptor)
{
return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoderWithDescriptor_), computePassDescriptor);
}
_MTL_INLINE MTL::BlitCommandEncoder* MTL::CommandBuffer::blitCommandEncoder(const MTL::BlitPassDescriptor* blitPassDescriptor)
{
return Object::sendMessage<MTL::BlitCommandEncoder*>(this, _MTL_PRIVATE_SEL(blitCommandEncoderWithDescriptor_), blitPassDescriptor);
}
_MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder()
{
return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoder));
}
_MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder(MTL::DispatchType dispatchType)
{
return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoderWithDispatchType_), dispatchType);
}
_MTL_INLINE void MTL::CommandBuffer::encodeWait(const MTL::Event* event, uint64_t value)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(encodeWaitForEvent_value_), event, value);
}
_MTL_INLINE void MTL::CommandBuffer::encodeSignalEvent(const MTL::Event* event, uint64_t value)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(encodeSignalEvent_value_), event, value);
}
_MTL_INLINE MTL::ParallelRenderCommandEncoder* MTL::CommandBuffer::parallelRenderCommandEncoder(const MTL::RenderPassDescriptor* renderPassDescriptor)
{
return Object::sendMessage<MTL::ParallelRenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(parallelRenderCommandEncoderWithDescriptor_), renderPassDescriptor);
}
_MTL_INLINE MTL::ResourceStateCommandEncoder* MTL::CommandBuffer::resourceStateCommandEncoder()
{
return Object::sendMessage<MTL::ResourceStateCommandEncoder*>(this, _MTL_PRIVATE_SEL(resourceStateCommandEncoder));
}
_MTL_INLINE MTL::ResourceStateCommandEncoder* MTL::CommandBuffer::resourceStateCommandEncoder(const MTL::ResourceStatePassDescriptor* resourceStatePassDescriptor)
{
return Object::sendMessage<MTL::ResourceStateCommandEncoder*>(this, _MTL_PRIVATE_SEL(resourceStateCommandEncoderWithDescriptor_), resourceStatePassDescriptor);
}
_MTL_INLINE MTL::AccelerationStructureCommandEncoder* MTL::CommandBuffer::accelerationStructureCommandEncoder()
{
return Object::sendMessage<MTL::AccelerationStructureCommandEncoder*>(this, _MTL_PRIVATE_SEL(accelerationStructureCommandEncoder));
}
_MTL_INLINE void MTL::CommandBuffer::pushDebugGroup(const NS::String* string)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(pushDebugGroup_), string);
}
_MTL_INLINE void MTL::CommandBuffer::popDebugGroup()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(popDebugGroup));
}
#pragma once
namespace MTL
{
class CommandQueue : public NS::Referencing<CommandQueue>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
class CommandBuffer* commandBuffer();
class CommandBuffer* commandBuffer(const class CommandBufferDescriptor* descriptor);
class CommandBuffer* commandBufferWithUnretainedReferences();
void insertDebugCaptureBoundary();
};
}
_MTL_INLINE NS::String* MTL::CommandQueue::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::CommandQueue::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::CommandQueue::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBuffer()
{
return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBuffer));
}
_MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBuffer(const MTL::CommandBufferDescriptor* descriptor)
{
return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBufferWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBufferWithUnretainedReferences()
{
return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBufferWithUnretainedReferences));
}
_MTL_INLINE void MTL::CommandQueue::insertDebugCaptureBoundary()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(insertDebugCaptureBoundary));
}
#pragma once
namespace MTL
{
struct DispatchThreadgroupsIndirectArguments
{
uint32_t threadgroupsPerGrid[3];
} _MTL_PACKED;
struct StageInRegionIndirectArguments
{
uint32_t stageInOrigin[3];
uint32_t stageInSize[3];
} _MTL_PACKED;
class ComputeCommandEncoder : public NS::Referencing<ComputeCommandEncoder, CommandEncoder>
{
public:
MTL::DispatchType dispatchType() const;
void setComputePipelineState(const class ComputePipelineState* state);
void setBytes(const void* bytes, NS::UInteger length, NS::UInteger index);
void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setBufferOffset(NS::UInteger offset, NS::UInteger index);
void setBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range);
void setVisibleFunctionTable(const class VisibleFunctionTable* visibleFunctionTable, NS::UInteger bufferIndex);
void setVisibleFunctionTables(const class VisibleFunctionTable* visibleFunctionTables[], NS::Range range);
void setIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex);
void setIntersectionFunctionTables(const class IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range);
void setAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex);
void setTexture(const class Texture* texture, NS::UInteger index);
void setTextures(MTL::Texture* textures[], NS::Range range);
void setSamplerState(const class SamplerState* sampler, NS::UInteger index);
void setSamplerStates(MTL::SamplerState* samplers[], NS::Range range);
void setSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index);
void setSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range);
void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index);
void setImageblockWidth(NS::UInteger width, NS::UInteger height);
void setStageInRegion(MTL::Region region);
void setStageInRegion(const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
void dispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup);
void dispatchThreadgroups(const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerThreadgroup);
void dispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup);
void updateFence(const class Fence* fence);
void waitForFence(const class Fence* fence);
void useResource(const class Resource* resource, MTL::ResourceUsage usage);
void useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage);
void useHeap(const class Heap* heap);
void useHeaps(MTL::Heap* heaps[], NS::UInteger count);
void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange);
void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandbuffer, const class Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset);
void memoryBarrier(MTL::BarrierScope scope);
void memoryBarrier(MTL::Resource* resources[], NS::UInteger count);
void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier);
};
}
_MTL_INLINE MTL::DispatchType MTL::ComputeCommandEncoder::dispatchType() const
{
return Object::sendMessage<MTL::DispatchType>(this, _MTL_PRIVATE_SEL(dispatchType));
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setComputePipelineState(const MTL::ComputePipelineState* state)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_), state);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setBytes(const void* bytes, NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBytes_length_atIndex_), bytes, length, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setBufferOffset(NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferOffset_atIndex_), offset, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setBuffers(MTL::Buffer* buffers[], const NS::UInteger offsets[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setVisibleFunctionTable(const MTL::VisibleFunctionTable* visibleFunctionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atBufferIndex_), visibleFunctionTable, bufferIndex);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setVisibleFunctionTables(const MTL::VisibleFunctionTable* visibleFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withBufferRange_), visibleFunctionTables, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setIntersectionFunctionTables(const MTL::IntersectionFunctionTable* intersectionFunctionTables[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setTexture(const MTL::Texture* texture, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_atIndex_), texture, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setTextures(MTL::Texture* textures[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextures_withRange_), textures, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerState(const MTL::SamplerState* sampler, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_atIndex_), sampler, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerStates(MTL::SamplerState* samplers[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_withRange_), samplers, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerStates(MTL::SamplerState* samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_atIndex_), length, index);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setImageblockWidth(NS::UInteger width, NS::UInteger height)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockWidth_height_), width, height);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setStageInRegion(MTL::Region region)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegion_), region);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::setStageInRegion(const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegionWithIndirectBuffer_indirectBufferOffset_), indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadgroups_threadsPerThreadgroup_), threadgroupsPerGrid, threadsPerThreadgroup);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreadgroups(const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup_), indirectBuffer, indirectBufferOffset, threadsPerThreadgroup);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreads_threadsPerThreadgroup_), threadsPerGrid, threadsPerThreadgroup);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::updateFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::waitForFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::useResources(MTL::Resource* resources[], NS::UInteger count, MTL::ResourceUsage usage)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::useHeap(const MTL::Heap* heap)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::useHeaps(MTL::Heap* heaps[], NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_withRange_), indirectCommandBuffer, executionRange);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandbuffer, const MTL::Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_), indirectCommandbuffer, indirectRangeBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::memoryBarrier(MTL::BarrierScope scope)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithScope_), scope);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::memoryBarrier(MTL::Resource* resources[], NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithResources_count_), resources, count);
}
_MTL_INLINE void MTL::ComputeCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier);
}
#pragma once
namespace MTL
{
class ComputePassSampleBufferAttachmentDescriptor : public NS::Copying<ComputePassSampleBufferAttachmentDescriptor>
{
public:
static class ComputePassSampleBufferAttachmentDescriptor* alloc();
class ComputePassSampleBufferAttachmentDescriptor* init();
class CounterSampleBuffer* sampleBuffer() const;
void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer);
NS::UInteger startOfEncoderSampleIndex() const;
void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex);
NS::UInteger endOfEncoderSampleIndex() const;
void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex);
};
class ComputePassSampleBufferAttachmentDescriptorArray : public NS::Referencing<ComputePassSampleBufferAttachmentDescriptorArray>
{
public:
static class ComputePassSampleBufferAttachmentDescriptorArray* alloc();
class ComputePassSampleBufferAttachmentDescriptorArray* init();
class ComputePassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class ComputePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class ComputePassDescriptor : public NS::Copying<ComputePassDescriptor>
{
public:
static class ComputePassDescriptor* alloc();
class ComputePassDescriptor* init();
static class ComputePassDescriptor* computePassDescriptor();
MTL::DispatchType dispatchType() const;
void setDispatchType(MTL::DispatchType dispatchType);
class ComputePassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const;
};
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::ComputePassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLComputePassSampleBufferAttachmentDescriptor));
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptor::init()
{
return NS::Object::init<MTL::ComputePassSampleBufferAttachmentDescriptor>();
}
_MTL_INLINE MTL::CounterSampleBuffer* MTL::ComputePassSampleBufferAttachmentDescriptor::sampleBuffer() const
{
return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer));
}
_MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer);
}
_MTL_INLINE NS::UInteger MTL::ComputePassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::ComputePassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex);
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassSampleBufferAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::ComputePassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLComputePassSampleBufferAttachmentDescriptorArray));
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassSampleBufferAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::ComputePassSampleBufferAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::ComputePassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptorArray::setObject(const MTL::ComputePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::alloc()
{
return NS::Object::alloc<MTL::ComputePassDescriptor>(_MTL_PRIVATE_CLS(MTLComputePassDescriptor));
}
_MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::init()
{
return NS::Object::init<MTL::ComputePassDescriptor>();
}
_MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::computePassDescriptor()
{
return Object::sendMessage<MTL::ComputePassDescriptor*>(_MTL_PRIVATE_CLS(MTLComputePassDescriptor), _MTL_PRIVATE_SEL(computePassDescriptor));
}
_MTL_INLINE MTL::DispatchType MTL::ComputePassDescriptor::dispatchType() const
{
return Object::sendMessage<MTL::DispatchType>(this, _MTL_PRIVATE_SEL(dispatchType));
}
_MTL_INLINE void MTL::ComputePassDescriptor::setDispatchType(MTL::DispatchType dispatchType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDispatchType_), dispatchType);
}
_MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassDescriptor::sampleBufferAttachments() const
{
return Object::sendMessage<MTL::ComputePassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments));
}
#pragma once
namespace MTL
{
_MTL_CONST( NS::ErrorDomain, CounterErrorDomain );
using CommonCounter = NS::String*;
_MTL_CONST( CommonCounter, CommonCounterTimestamp );
_MTL_CONST( CommonCounter, CommonCounterTessellationInputPatches );
_MTL_CONST( CommonCounter, CommonCounterVertexInvocations );
_MTL_CONST( CommonCounter, CommonCounterPostTessellationVertexInvocations );
_MTL_CONST( CommonCounter, CommonCounterClipperInvocations );
_MTL_CONST( CommonCounter, CommonCounterClipperPrimitivesOut );
_MTL_CONST( CommonCounter, CommonCounterFragmentInvocations );
_MTL_CONST( CommonCounter, CommonCounterFragmentsPassed );
_MTL_CONST( CommonCounter, CommonCounterComputeKernelInvocations );
_MTL_CONST( CommonCounter, CommonCounterTotalCycles );
_MTL_CONST( CommonCounter, CommonCounterVertexCycles );
_MTL_CONST( CommonCounter, CommonCounterTessellationCycles );
_MTL_CONST( CommonCounter, CommonCounterPostTessellationVertexCycles );
_MTL_CONST( CommonCounter, CommonCounterFragmentCycles );
_MTL_CONST( CommonCounter, CommonCounterRenderTargetWriteCycles );
using CommonCounterSet = NS::String*;
_MTL_CONST( CommonCounterSet, CommonCounterSetTimestamp );
_MTL_CONST( CommonCounterSet, CommonCounterSetStageUtilization );
_MTL_CONST( CommonCounterSet, CommonCounterSetStatistic );
struct CounterResultTimestamp
{
uint64_t timestamp;
} _MTL_PACKED;
struct CounterResultStageUtilization
{
uint64_t totalCycles;
uint64_t vertexCycles;
uint64_t tessellationCycles;
uint64_t postTessellationVertexCycles;
uint64_t fragmentCycles;
uint64_t renderTargetCycles;
} _MTL_PACKED;
struct CounterResultStatistic
{
uint64_t tessellationInputPatches;
uint64_t vertexInvocations;
uint64_t postTessellationVertexInvocations;
uint64_t clipperInvocations;
uint64_t clipperPrimitivesOut;
uint64_t fragmentInvocations;
uint64_t fragmentsPassed;
uint64_t computeKernelInvocations;
} _MTL_PACKED;
class Counter : public NS::Referencing<Counter>
{
public:
NS::String* name() const;
};
class CounterSet : public NS::Referencing<CounterSet>
{
public:
NS::String* name() const;
NS::Array* counters() const;
};
class CounterSampleBufferDescriptor : public NS::Copying<CounterSampleBufferDescriptor>
{
public:
static class CounterSampleBufferDescriptor* alloc();
class CounterSampleBufferDescriptor* init();
class CounterSet* counterSet() const;
void setCounterSet(const class CounterSet* counterSet);
NS::String* label() const;
void setLabel(const NS::String* label);
MTL::StorageMode storageMode() const;
void setStorageMode(MTL::StorageMode storageMode);
NS::UInteger sampleCount() const;
void setSampleCount(NS::UInteger sampleCount);
};
class CounterSampleBuffer : public NS::Referencing<CounterSampleBuffer>
{
public:
class Device* device() const;
NS::String* label() const;
NS::UInteger sampleCount() const;
NS::Data* resolveCounterRange(NS::Range range);
};
_MTL_ENUM(NS::Integer, CounterSampleBufferError) {
CounterSampleBufferErrorOutOfMemory = 0,
CounterSampleBufferErrorInvalid = 1,
};
}
_MTL_PRIVATE_DEF_STR( NS::ErrorDomain, CounterErrorDomain );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterTimestamp );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterTessellationInputPatches );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterVertexInvocations );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterPostTessellationVertexInvocations );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterClipperInvocations );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterClipperPrimitivesOut );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterFragmentInvocations );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterFragmentsPassed );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterComputeKernelInvocations );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterTotalCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterVertexCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterTessellationCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterPostTessellationVertexCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterFragmentCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounter, CommonCounterRenderTargetWriteCycles );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounterSet, CommonCounterSetTimestamp );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounterSet, CommonCounterSetStageUtilization );
_MTL_PRIVATE_DEF_STR( MTL::CommonCounterSet, CommonCounterSetStatistic );
_MTL_INLINE NS::String* MTL::Counter::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::String* MTL::CounterSet::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE NS::Array* MTL::CounterSet::counters() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(counters));
}
_MTL_INLINE MTL::CounterSampleBufferDescriptor* MTL::CounterSampleBufferDescriptor::alloc()
{
return NS::Object::alloc<MTL::CounterSampleBufferDescriptor>(_MTL_PRIVATE_CLS(MTLCounterSampleBufferDescriptor));
}
_MTL_INLINE MTL::CounterSampleBufferDescriptor* MTL::CounterSampleBufferDescriptor::init()
{
return NS::Object::init<MTL::CounterSampleBufferDescriptor>();
}
_MTL_INLINE MTL::CounterSet* MTL::CounterSampleBufferDescriptor::counterSet() const
{
return Object::sendMessage<MTL::CounterSet*>(this, _MTL_PRIVATE_SEL(counterSet));
}
_MTL_INLINE void MTL::CounterSampleBufferDescriptor::setCounterSet(const MTL::CounterSet* counterSet)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCounterSet_), counterSet);
}
_MTL_INLINE NS::String* MTL::CounterSampleBufferDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::CounterSampleBufferDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::StorageMode MTL::CounterSampleBufferDescriptor::storageMode() const
{
return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode));
}
_MTL_INLINE void MTL::CounterSampleBufferDescriptor::setStorageMode(MTL::StorageMode storageMode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode);
}
_MTL_INLINE NS::UInteger MTL::CounterSampleBufferDescriptor::sampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE void MTL::CounterSampleBufferDescriptor::setSampleCount(NS::UInteger sampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount);
}
_MTL_INLINE MTL::Device* MTL::CounterSampleBuffer::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::CounterSampleBuffer::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE NS::UInteger MTL::CounterSampleBuffer::sampleCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE NS::Data* MTL::CounterSampleBuffer::resolveCounterRange(NS::Range range)
{
return Object::sendMessage<NS::Data*>(this, _MTL_PRIVATE_SEL(resolveCounterRange_), range);
}
#pragma once
#include <IOSurface/IOSurfaceRef.h>
#include <functional>
namespace MTL
{
_MTL_ENUM(NS::UInteger, FeatureSet) {
FeatureSet_iOS_GPUFamily1_v1 = 0,
FeatureSet_iOS_GPUFamily2_v1 = 1,
FeatureSet_iOS_GPUFamily1_v2 = 2,
FeatureSet_iOS_GPUFamily2_v2 = 3,
FeatureSet_iOS_GPUFamily3_v1 = 4,
FeatureSet_iOS_GPUFamily1_v3 = 5,
FeatureSet_iOS_GPUFamily2_v3 = 6,
FeatureSet_iOS_GPUFamily3_v2 = 7,
FeatureSet_iOS_GPUFamily1_v4 = 8,
FeatureSet_iOS_GPUFamily2_v4 = 9,
FeatureSet_iOS_GPUFamily3_v3 = 10,
FeatureSet_iOS_GPUFamily4_v1 = 11,
FeatureSet_iOS_GPUFamily1_v5 = 12,
FeatureSet_iOS_GPUFamily2_v5 = 13,
FeatureSet_iOS_GPUFamily3_v4 = 14,
FeatureSet_iOS_GPUFamily4_v2 = 15,
FeatureSet_iOS_GPUFamily5_v1 = 16,
FeatureSet_macOS_GPUFamily1_v1 = 10000,
FeatureSet_OSX_GPUFamily1_v1 = 10000,
FeatureSet_macOS_GPUFamily1_v2 = 10001,
FeatureSet_OSX_GPUFamily1_v2 = 10001,
FeatureSet_OSX_ReadWriteTextureTier2 = 10002,
FeatureSet_macOS_ReadWriteTextureTier2 = 10002,
FeatureSet_macOS_GPUFamily1_v3 = 10003,
FeatureSet_macOS_GPUFamily1_v4 = 10004,
FeatureSet_macOS_GPUFamily2_v1 = 10005,
FeatureSet_watchOS_GPUFamily1_v1 = 20000,
FeatureSet_WatchOS_GPUFamily1_v1 = 20000,
FeatureSet_watchOS_GPUFamily2_v1 = 20001,
FeatureSet_WatchOS_GPUFamily2_v1 = 20001,
FeatureSet_tvOS_GPUFamily1_v1 = 30000,
FeatureSet_TVOS_GPUFamily1_v1 = 30000,
FeatureSet_tvOS_GPUFamily1_v2 = 30001,
FeatureSet_tvOS_GPUFamily1_v3 = 30002,
FeatureSet_tvOS_GPUFamily2_v1 = 30003,
FeatureSet_tvOS_GPUFamily1_v4 = 30004,
FeatureSet_tvOS_GPUFamily2_v2 = 30005,
};
_MTL_ENUM(NS::Integer, GPUFamily) {
GPUFamilyApple1 = 1001,
GPUFamilyApple2 = 1002,
GPUFamilyApple3 = 1003,
GPUFamilyApple4 = 1004,
GPUFamilyApple5 = 1005,
GPUFamilyApple6 = 1006,
GPUFamilyApple7 = 1007,
GPUFamilyApple8 = 1008,
GPUFamilyMac1 = 2001,
GPUFamilyMac2 = 2002,
GPUFamilyCommon1 = 3001,
GPUFamilyCommon2 = 3002,
GPUFamilyCommon3 = 3003,
GPUFamilyMacCatalyst1 = 4001,
GPUFamilyMacCatalyst2 = 4002,
};
_MTL_ENUM(NS::UInteger, DeviceLocation) {
DeviceLocationBuiltIn = 0,
DeviceLocationSlot = 1,
DeviceLocationExternal = 2,
DeviceLocationUnspecified = NS::UIntegerMax,
};
_MTL_OPTIONS(NS::UInteger, PipelineOption) {
PipelineOptionNone = 0,
PipelineOptionArgumentInfo = 1,
PipelineOptionBufferTypeInfo = 2,
PipelineOptionFailOnBinaryArchiveMiss = 4,
};
_MTL_ENUM(NS::UInteger, ReadWriteTextureTier) {
ReadWriteTextureTierNone = 0,
ReadWriteTextureTier1 = 1,
ReadWriteTextureTier2 = 2,
};
_MTL_ENUM(NS::UInteger, ArgumentBuffersTier) {
ArgumentBuffersTier1 = 0,
ArgumentBuffersTier2 = 1,
};
_MTL_ENUM(NS::UInteger, SparseTextureRegionAlignmentMode) {
SparseTextureRegionAlignmentModeOutward = 0,
SparseTextureRegionAlignmentModeInward = 1,
};
struct AccelerationStructureSizes
{
NS::UInteger accelerationStructureSize;
NS::UInteger buildScratchBufferSize;
NS::UInteger refitScratchBufferSize;
} _MTL_PACKED;
_MTL_ENUM(NS::UInteger, CounterSamplingPoint) {
CounterSamplingPointAtStageBoundary = 0,
CounterSamplingPointAtDrawBoundary = 1,
CounterSamplingPointAtDispatchBoundary = 2,
CounterSamplingPointAtTileDispatchBoundary = 3,
CounterSamplingPointAtBlitBoundary = 4,
};
struct SizeAndAlign
{
NS::UInteger size;
NS::UInteger align;
} _MTL_PACKED;
class ArgumentDescriptor : public NS::Copying<ArgumentDescriptor>
{
public:
static class ArgumentDescriptor* alloc();
class ArgumentDescriptor* init();
static class ArgumentDescriptor* argumentDescriptor();
MTL::DataType dataType() const;
void setDataType(MTL::DataType dataType);
NS::UInteger index() const;
void setIndex(NS::UInteger index);
NS::UInteger arrayLength() const;
void setArrayLength(NS::UInteger arrayLength);
MTL::ArgumentAccess access() const;
void setAccess(MTL::ArgumentAccess access);
MTL::TextureType textureType() const;
void setTextureType(MTL::TextureType textureType);
NS::UInteger constantBlockAlignment() const;
void setConstantBlockAlignment(NS::UInteger constantBlockAlignment);
};
using DeviceNotificationName = NS::String*;
_MTL_CONST(DeviceNotificationName, DeviceWasAddedNotification);
_MTL_CONST(DeviceNotificationName, DeviceRemovalRequestedNotification);
_MTL_CONST(DeviceNotificationName, DeviceWasRemovedNotification);
using DeviceNotificationHandlerBlock = void (^)(class Device* pDevice, DeviceNotificationName notifyName);
using DeviceNotificationHandlerFunction = std::function<void(class Device* pDevice, DeviceNotificationName notifyName)>;
using AutoreleasedComputePipelineReflection = class ComputePipelineReflection*;
using AutoreleasedRenderPipelineReflection = class RenderPipelineReflection*;
using NewLibraryCompletionHandler = void (^)(class Library*, NS::Error*);
using NewLibraryCompletionHandlerFunction = std::function<void(class Library*, NS::Error*)>;
using NewRenderPipelineStateCompletionHandler = void (^)(class RenderPipelineState*, NS::Error*);
using NewRenderPipelineStateCompletionHandlerFunction = std::function<void(class RenderPipelineState*, NS::Error*)>;
using NewRenderPipelineStateWithReflectionCompletionHandler = void (^)(class RenderPipelineState*, class RenderPipelineReflection*, NS::Error*);
using NewRenderPipelineStateWithReflectionCompletionHandlerFunction = std::function<void(class RenderPipelineState*, class RenderPipelineReflection*, NS::Error*)>;
using NewComputePipelineStateCompletionHandler = void (^)(class ComputePipelineState*, NS::Error*);
using NewComputePipelineStateCompletionHandlerFunction = std::function<void(class ComputePipelineState*, NS::Error*)>;
using NewComputePipelineStateWithReflectionCompletionHandler = void (^)(class ComputePipelineState*, class ComputePipelineReflection*, NS::Error*);
using NewComputePipelineStateWithReflectionCompletionHandlerFunction = std::function<void(class ComputePipelineState*, class ComputePipelineReflection*, NS::Error*)>;
using Timestamp = std::uint64_t;
MTL::Device* CreateSystemDefaultDevice();
NS::Array* CopyAllDevices();
NS::Array* CopyAllDevicesWithObserver(NS::Object** pOutObserver, DeviceNotificationHandlerBlock handler);
NS::Array* CopyAllDevicesWithObserver(NS::Object** pOutObserver, const DeviceNotificationHandlerFunction& handler);
void RemoveDeviceObserver(const NS::Object* pObserver);
class Device : public NS::Referencing<Device>
{
public:
void newLibrary(const NS::String* pSource, const class CompileOptions* pOptions, const NewLibraryCompletionHandlerFunction& completionHandler);
void newLibrary(const class StitchedLibraryDescriptor* pDescriptor, const MTL::NewLibraryCompletionHandlerFunction& completionHandler);
void newRenderPipelineState(const class RenderPipelineDescriptor* pDescriptor, const NewRenderPipelineStateCompletionHandlerFunction& completionHandler);
void newRenderPipelineState(const class RenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler);
void newRenderPipelineState(const class TileRenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler);
void newComputePipelineState(const class Function* pFunction, const NewComputePipelineStateCompletionHandlerFunction& completionHandler);
void newComputePipelineState(const class Function* pFunction, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler);
void newComputePipelineState(const class ComputePipelineDescriptor* pDescriptor, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler);
bool isHeadless() const;
NS::String* name() const;
uint64_t registryID() const;
MTL::Size maxThreadsPerThreadgroup() const;
bool lowPower() const;
bool headless() const;
bool removable() const;
bool hasUnifiedMemory() const;
uint64_t recommendedMaxWorkingSetSize() const;
MTL::DeviceLocation location() const;
NS::UInteger locationNumber() const;
uint64_t maxTransferRate() const;
bool depth24Stencil8PixelFormatSupported() const;
MTL::ReadWriteTextureTier readWriteTextureSupport() const;
MTL::ArgumentBuffersTier argumentBuffersSupport() const;
bool rasterOrderGroupsSupported() const;
bool supports32BitFloatFiltering() const;
bool supports32BitMSAA() const;
bool supportsQueryTextureLOD() const;
bool supportsBCTextureCompression() const;
bool supportsPullModelInterpolation() const;
bool barycentricCoordsSupported() const;
bool supportsShaderBarycentricCoordinates() const;
NS::UInteger currentAllocatedSize() const;
class CommandQueue* newCommandQueue();
class CommandQueue* newCommandQueue(NS::UInteger maxCommandBufferCount);
MTL::SizeAndAlign heapTextureSizeAndAlign(const class TextureDescriptor* desc);
MTL::SizeAndAlign heapBufferSizeAndAlign(NS::UInteger length, MTL::ResourceOptions options);
class Heap* newHeap(const class HeapDescriptor* descriptor);
class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options);
class Buffer* newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options);
class Buffer* newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options, void (^deallocator)(void*, NS::UInteger));
class DepthStencilState* newDepthStencilState(const class DepthStencilDescriptor* descriptor);
class Texture* newTexture(const class TextureDescriptor* descriptor);
class Texture* newTexture(const class TextureDescriptor* descriptor, const IOSurfaceRef iosurface, NS::UInteger plane);
class Texture* newSharedTexture(const class TextureDescriptor* descriptor);
class Texture* newSharedTexture(const class SharedTextureHandle* sharedHandle);
class SamplerState* newSamplerState(const class SamplerDescriptor* descriptor);
class Library* newDefaultLibrary();
class Library* newDefaultLibrary(const NS::Bundle* bundle, NS::Error** error);
class Library* newLibrary(const NS::String* filepath, NS::Error** error);
class Library* newLibrary(const NS::URL* url, NS::Error** error);
class Library* newLibrary(const dispatch_data_t data, NS::Error** error);
class Library* newLibrary(const NS::String* source, const class CompileOptions* options, NS::Error** error);
void newLibrary(const NS::String* source, const class CompileOptions* options, const MTL::NewLibraryCompletionHandler completionHandler);
class Library* newLibrary(const class StitchedLibraryDescriptor* descriptor, NS::Error** error);
void newLibrary(const class StitchedLibraryDescriptor* descriptor, const MTL::NewLibraryCompletionHandler completionHandler);
class RenderPipelineState* newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, NS::Error** error);
class RenderPipelineState* newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error);
void newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, const MTL::NewRenderPipelineStateCompletionHandler completionHandler);
void newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler);
class ComputePipelineState* newComputePipelineState(const class Function* computeFunction, NS::Error** error);
class ComputePipelineState* newComputePipelineState(const class Function* computeFunction, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error);
void newComputePipelineState(const class Function* computeFunction, const MTL::NewComputePipelineStateCompletionHandler completionHandler);
void newComputePipelineState(const class Function* computeFunction, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler);
class ComputePipelineState* newComputePipelineState(const class ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error);
void newComputePipelineState(const class ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler);
class Fence* newFence();
bool supportsFeatureSet(MTL::FeatureSet featureSet);
bool supportsFamily(MTL::GPUFamily gpuFamily);
bool supportsTextureSampleCount(NS::UInteger sampleCount);
NS::UInteger minimumLinearTextureAlignmentForPixelFormat(MTL::PixelFormat format);
NS::UInteger minimumTextureBufferAlignmentForPixelFormat(MTL::PixelFormat format);
class RenderPipelineState* newRenderPipelineState(const class TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error);
void newRenderPipelineState(const class TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler);
NS::UInteger maxThreadgroupMemoryLength() const;
NS::UInteger maxArgumentBufferSamplerCount() const;
bool programmableSamplePositionsSupported() const;
void getDefaultSamplePositions(MTL::SamplePosition* positions, NS::UInteger count);
class ArgumentEncoder* newArgumentEncoder(const NS::Array* arguments);
bool supportsRasterizationRateMap(NS::UInteger layerCount);
class RasterizationRateMap* newRasterizationRateMap(const class RasterizationRateMapDescriptor* descriptor);
class IndirectCommandBuffer* newIndirectCommandBuffer(const class IndirectCommandBufferDescriptor* descriptor, NS::UInteger maxCount, MTL::ResourceOptions options);
class Event* newEvent();
class SharedEvent* newSharedEvent();
class SharedEvent* newSharedEvent(const class SharedEventHandle* sharedEventHandle);
uint64_t peerGroupID() const;
uint32_t peerIndex() const;
uint32_t peerCount() const;
MTL::Size sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount);
NS::UInteger sparseTileSizeInBytes() const;
void convertSparsePixelRegions(const MTL::Region* pixelRegions, MTL::Region* tileRegions, MTL::Size tileSize, MTL::SparseTextureRegionAlignmentMode mode, NS::UInteger numRegions);
void convertSparseTileRegions(const MTL::Region* tileRegions, MTL::Region* pixelRegions, MTL::Size tileSize, NS::UInteger numRegions);
NS::UInteger maxBufferLength() const;
NS::Array* counterSets() const;
class CounterSampleBuffer* newCounterSampleBuffer(const class CounterSampleBufferDescriptor* descriptor, NS::Error** error);
void sampleTimestamps(MTL::Timestamp* cpuTimestamp, MTL::Timestamp* gpuTimestamp);
bool supportsCounterSampling(MTL::CounterSamplingPoint samplingPoint);
bool supportsVertexAmplificationCount(NS::UInteger count);
bool supportsDynamicLibraries() const;
bool supportsRenderDynamicLibraries() const;
class DynamicLibrary* newDynamicLibrary(const class Library* library, NS::Error** error);
class DynamicLibrary* newDynamicLibrary(const NS::URL* url, NS::Error** error);
class BinaryArchive* newBinaryArchive(const class BinaryArchiveDescriptor* descriptor, NS::Error** error);
bool supportsRaytracing() const;
MTL::AccelerationStructureSizes accelerationStructureSizes(const class AccelerationStructureDescriptor* descriptor);
class AccelerationStructure* newAccelerationStructure(NS::UInteger size);
class AccelerationStructure* newAccelerationStructure(const class AccelerationStructureDescriptor* descriptor);
bool supportsFunctionPointers() const;
bool supportsFunctionPointersFromRender() const;
bool supportsRaytracingFromRender() const;
bool supportsPrimitiveMotionBlur() const;
};
}
_MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::alloc()
{
return NS::Object::alloc<MTL::ArgumentDescriptor>(_MTL_PRIVATE_CLS(MTLArgumentDescriptor));
}
_MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::init()
{
return NS::Object::init<MTL::ArgumentDescriptor>();
}
_MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::argumentDescriptor()
{
return Object::sendMessage<MTL::ArgumentDescriptor*>(_MTL_PRIVATE_CLS(MTLArgumentDescriptor), _MTL_PRIVATE_SEL(argumentDescriptor));
}
_MTL_INLINE MTL::DataType MTL::ArgumentDescriptor::dataType() const
{
return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setDataType(MTL::DataType dataType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDataType_), dataType);
}
_MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::index() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setIndex(NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndex_), index);
}
_MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::arrayLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setArrayLength(NS::UInteger arrayLength)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArrayLength_), arrayLength);
}
_MTL_INLINE MTL::ArgumentAccess MTL::ArgumentDescriptor::access() const
{
return Object::sendMessage<MTL::ArgumentAccess>(this, _MTL_PRIVATE_SEL(access));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setAccess(MTL::ArgumentAccess access)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccess_), access);
}
_MTL_INLINE MTL::TextureType MTL::ArgumentDescriptor::textureType() const
{
return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setTextureType(MTL::TextureType textureType)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextureType_), textureType);
}
_MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::constantBlockAlignment() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(constantBlockAlignment));
}
_MTL_INLINE void MTL::ArgumentDescriptor::setConstantBlockAlignment(NS::UInteger constantBlockAlignment)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantBlockAlignment_), constantBlockAlignment);
}
#if defined(MTL_PRIVATE_IMPLEMENTATION)
extern "C" MTL::Device* MTLCreateSystemDefaultDevice();
extern "C" NS::Array* MTLCopyAllDevices();
extern "C" NS::Array* MTLCopyAllDevicesWithObserver(NS::Object**, MTL::DeviceNotificationHandlerBlock);
extern "C" void MTLRemoveDeviceObserver(const NS::Object*);
#include <TargetConditionals.h>
MTL::Device* MTL::CreateSystemDefaultDevice()
{
return ::MTLCreateSystemDefaultDevice();
}
NS::Array* MTL::CopyAllDevices()
{
#if TARGET_OS_OSX
return ::MTLCopyAllDevices();
#else
return nullptr;
#endif // TARGET_OS_OSX
}
NS::Array* MTL::CopyAllDevicesWithObserver(NS::Object** pOutObserver, DeviceNotificationHandlerBlock handler)
{
#if TARGET_OS_OSX
return ::MTLCopyAllDevicesWithObserver(pOutObserver, handler);
#else
(void)pOutObserver;
(void)handler;
return nullptr;
#endif // TARGET_OS_OSX
}
NS::Array* MTL::CopyAllDevicesWithObserver(NS::Object** pOutObserver, const DeviceNotificationHandlerFunction& handler)
{
__block DeviceNotificationHandlerFunction function = handler;
return CopyAllDevicesWithObserver(pOutObserver, ^(Device* pDevice, DeviceNotificationName pNotificationName) { function(pDevice, pNotificationName); });
}
void MTL::RemoveDeviceObserver(const NS::Object* pObserver)
{
#if TARGET_OS_OSX
::MTLRemoveDeviceObserver(pObserver);
#endif // TARGET_OS_OSX
}
#endif // MTL_PRIVATE_IMPLEMENTATION
_MTL_INLINE void MTL::Device::newLibrary(const NS::String* pSource, const CompileOptions* pOptions, const NewLibraryCompletionHandlerFunction& completionHandler)
{
__block NewLibraryCompletionHandlerFunction blockCompletionHandler = completionHandler;
newLibrary(pSource, pOptions, ^(Library* pLibrary, NS::Error* pError) { blockCompletionHandler(pLibrary, pError); });
}
_MTL_INLINE void MTL::Device::newLibrary(const class StitchedLibraryDescriptor* pDescriptor, const MTL::NewLibraryCompletionHandlerFunction& completionHandler)
{
__block NewLibraryCompletionHandlerFunction blockCompletionHandler = completionHandler;
newLibrary(pDescriptor, ^(Library* pLibrary, NS::Error* pError) { blockCompletionHandler(pLibrary, pError); });
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const RenderPipelineDescriptor* pDescriptor, const NewRenderPipelineStateCompletionHandlerFunction& completionHandler)
{
__block NewRenderPipelineStateCompletionHandlerFunction blockCompletionHandler = completionHandler;
newRenderPipelineState(pDescriptor, ^(RenderPipelineState* pPipelineState, NS::Error* pError) { blockCompletionHandler(pPipelineState, pError); });
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const RenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler)
{
__block NewRenderPipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler;
newRenderPipelineState(pDescriptor, options, ^(RenderPipelineState* pPipelineState, class RenderPipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); });
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const TileRenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler)
{
__block NewRenderPipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler;
newRenderPipelineState(pDescriptor, options, ^(RenderPipelineState* pPipelineState, class RenderPipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); });
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const class Function* pFunction, const NewComputePipelineStateCompletionHandlerFunction& completionHandler)
{
__block NewComputePipelineStateCompletionHandlerFunction blockCompletionHandler = completionHandler;
newComputePipelineState(pFunction, ^(ComputePipelineState* pPipelineState, NS::Error* pError) { blockCompletionHandler(pPipelineState, pError); });
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const Function* pFunction, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler)
{
__block NewComputePipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler;
newComputePipelineState(pFunction, options, ^(ComputePipelineState* pPipelineState, ComputePipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); });
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const ComputePipelineDescriptor* pDescriptor, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler)
{
__block NewComputePipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler;
newComputePipelineState(pDescriptor, options, ^(ComputePipelineState* pPipelineState, ComputePipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); });
}
_MTL_INLINE bool MTL::Device::isHeadless() const
{
return headless();
}
_MTL_INLINE NS::String* MTL::Device::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE uint64_t MTL::Device::registryID() const
{
return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(registryID));
}
_MTL_INLINE MTL::Size MTL::Device::maxThreadsPerThreadgroup() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(maxThreadsPerThreadgroup));
}
_MTL_INLINE bool MTL::Device::lowPower() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isLowPower));
}
_MTL_INLINE bool MTL::Device::headless() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isHeadless));
}
_MTL_INLINE bool MTL::Device::removable() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isRemovable));
}
_MTL_INLINE bool MTL::Device::hasUnifiedMemory() const
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(hasUnifiedMemory));
}
_MTL_INLINE uint64_t MTL::Device::recommendedMaxWorkingSetSize() const
{
return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(recommendedMaxWorkingSetSize));
}
_MTL_INLINE MTL::DeviceLocation MTL::Device::location() const
{
return Object::sendMessage<MTL::DeviceLocation>(this, _MTL_PRIVATE_SEL(location));
}
_MTL_INLINE NS::UInteger MTL::Device::locationNumber() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(locationNumber));
}
_MTL_INLINE uint64_t MTL::Device::maxTransferRate() const
{
return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(maxTransferRate));
}
_MTL_INLINE bool MTL::Device::depth24Stencil8PixelFormatSupported() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(isDepth24Stencil8PixelFormatSupported));
}
_MTL_INLINE MTL::ReadWriteTextureTier MTL::Device::readWriteTextureSupport() const
{
return Object::sendMessage<MTL::ReadWriteTextureTier>(this, _MTL_PRIVATE_SEL(readWriteTextureSupport));
}
_MTL_INLINE MTL::ArgumentBuffersTier MTL::Device::argumentBuffersSupport() const
{
return Object::sendMessage<MTL::ArgumentBuffersTier>(this, _MTL_PRIVATE_SEL(argumentBuffersSupport));
}
_MTL_INLINE bool MTL::Device::rasterOrderGroupsSupported() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areRasterOrderGroupsSupported));
}
_MTL_INLINE bool MTL::Device::supports32BitFloatFiltering() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supports32BitFloatFiltering));
}
_MTL_INLINE bool MTL::Device::supports32BitMSAA() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supports32BitMSAA));
}
_MTL_INLINE bool MTL::Device::supportsQueryTextureLOD() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsQueryTextureLOD));
}
_MTL_INLINE bool MTL::Device::supportsBCTextureCompression() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsBCTextureCompression));
}
_MTL_INLINE bool MTL::Device::supportsPullModelInterpolation() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsPullModelInterpolation));
}
_MTL_INLINE bool MTL::Device::barycentricCoordsSupported() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areBarycentricCoordsSupported));
}
_MTL_INLINE bool MTL::Device::supportsShaderBarycentricCoordinates() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsShaderBarycentricCoordinates));
}
_MTL_INLINE NS::UInteger MTL::Device::currentAllocatedSize() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(currentAllocatedSize));
}
_MTL_INLINE MTL::CommandQueue* MTL::Device::newCommandQueue()
{
return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(newCommandQueue));
}
_MTL_INLINE MTL::CommandQueue* MTL::Device::newCommandQueue(NS::UInteger maxCommandBufferCount)
{
return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(newCommandQueueWithMaxCommandBufferCount_), maxCommandBufferCount);
}
_MTL_INLINE MTL::SizeAndAlign MTL::Device::heapTextureSizeAndAlign(const MTL::TextureDescriptor* desc)
{
return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapTextureSizeAndAlignWithDescriptor_), desc);
}
_MTL_INLINE MTL::SizeAndAlign MTL::Device::heapBufferSizeAndAlign(NS::UInteger length, MTL::ResourceOptions options)
{
return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapBufferSizeAndAlignWithLength_options_), length, options);
}
_MTL_INLINE MTL::Heap* MTL::Device::newHeap(const MTL::HeapDescriptor* descriptor)
{
return Object::sendMessage<MTL::Heap*>(this, _MTL_PRIVATE_SEL(newHeapWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(NS::UInteger length, MTL::ResourceOptions options)
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_), length, options);
}
_MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options)
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithBytes_length_options_), pointer, length, options);
}
_MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options, void (^deallocator)(void*, NS::UInteger))
{
return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithBytesNoCopy_length_options_deallocator_), pointer, length, options, deallocator);
}
_MTL_INLINE MTL::DepthStencilState* MTL::Device::newDepthStencilState(const MTL::DepthStencilDescriptor* descriptor)
{
return Object::sendMessage<MTL::DepthStencilState*>(this, _MTL_PRIVATE_SEL(newDepthStencilStateWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::Texture* MTL::Device::newTexture(const MTL::TextureDescriptor* descriptor)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::Texture* MTL::Device::newTexture(const MTL::TextureDescriptor* descriptor, const IOSurfaceRef iosurface, NS::UInteger plane)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_iosurface_plane_), descriptor, iosurface, plane);
}
_MTL_INLINE MTL::Texture* MTL::Device::newSharedTexture(const MTL::TextureDescriptor* descriptor)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newSharedTextureWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::Texture* MTL::Device::newSharedTexture(const MTL::SharedTextureHandle* sharedHandle)
{
return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newSharedTextureWithHandle_), sharedHandle);
}
_MTL_INLINE MTL::SamplerState* MTL::Device::newSamplerState(const MTL::SamplerDescriptor* descriptor)
{
return Object::sendMessage<MTL::SamplerState*>(this, _MTL_PRIVATE_SEL(newSamplerStateWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::Library* MTL::Device::newDefaultLibrary()
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newDefaultLibrary));
}
_MTL_INLINE MTL::Library* MTL::Device::newDefaultLibrary(const NS::Bundle* bundle, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newDefaultLibraryWithBundle_error_), bundle, error);
}
_MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::String* filepath, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithFile_error_), filepath, error);
}
_MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::URL* url, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithURL_error_), url, error);
}
_MTL_INLINE MTL::Library* MTL::Device::newLibrary(const dispatch_data_t data, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithData_error_), data, error);
}
_MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::String* source, const MTL::CompileOptions* options, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithSource_options_error_), source, options, error);
}
_MTL_INLINE void MTL::Device::newLibrary(const NS::String* source, const MTL::CompileOptions* options, const MTL::NewLibraryCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newLibraryWithSource_options_completionHandler_), source, options, completionHandler);
}
_MTL_INLINE MTL::Library* MTL::Device::newLibrary(const MTL::StitchedLibraryDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithStitchedDescriptor_error_), descriptor, error);
}
_MTL_INLINE void MTL::Device::newLibrary(const MTL::StitchedLibraryDescriptor* descriptor, const MTL::NewLibraryCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newLibraryWithStitchedDescriptor_completionHandler_), descriptor, completionHandler);
}
_MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error)
{
return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_options_reflection_error_), descriptor, options, reflection, error);
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, const MTL::NewRenderPipelineStateCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_completionHandler_), descriptor, completionHandler);
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_options_completionHandler_), descriptor, options, completionHandler);
}
_MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, NS::Error** error)
{
return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_error_), computeFunction, error);
}
_MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error)
{
return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_options_reflection_error_), computeFunction, options, reflection, error);
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, const MTL::NewComputePipelineStateCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_completionHandler_), computeFunction, completionHandler);
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_options_completionHandler_), computeFunction, options, completionHandler);
}
_MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error)
{
return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithDescriptor_options_reflection_error_), descriptor, options, reflection, error);
}
_MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithDescriptor_options_completionHandler_), descriptor, options, completionHandler);
}
_MTL_INLINE MTL::Fence* MTL::Device::newFence()
{
return Object::sendMessage<MTL::Fence*>(this, _MTL_PRIVATE_SEL(newFence));
}
_MTL_INLINE bool MTL::Device::supportsFeatureSet(MTL::FeatureSet featureSet)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFeatureSet_), featureSet);
}
_MTL_INLINE bool MTL::Device::supportsFamily(MTL::GPUFamily gpuFamily)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFamily_), gpuFamily);
}
_MTL_INLINE bool MTL::Device::supportsTextureSampleCount(NS::UInteger sampleCount)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsTextureSampleCount_), sampleCount);
}
_MTL_INLINE NS::UInteger MTL::Device::minimumLinearTextureAlignmentForPixelFormat(MTL::PixelFormat format)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(minimumLinearTextureAlignmentForPixelFormat_), format);
}
_MTL_INLINE NS::UInteger MTL::Device::minimumTextureBufferAlignmentForPixelFormat(MTL::PixelFormat format)
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(minimumTextureBufferAlignmentForPixelFormat_), format);
}
_MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error)
{
return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithTileDescriptor_options_reflection_error_), descriptor, options, reflection, error);
}
_MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithTileDescriptor_options_completionHandler_), descriptor, options, completionHandler);
}
_MTL_INLINE NS::UInteger MTL::Device::maxThreadgroupMemoryLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxThreadgroupMemoryLength));
}
_MTL_INLINE NS::UInteger MTL::Device::maxArgumentBufferSamplerCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxArgumentBufferSamplerCount));
}
_MTL_INLINE bool MTL::Device::programmableSamplePositionsSupported() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areProgrammableSamplePositionsSupported));
}
_MTL_INLINE void MTL::Device::getDefaultSamplePositions(MTL::SamplePosition* positions, NS::UInteger count)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getDefaultSamplePositions_count_), positions, count);
}
_MTL_INLINE MTL::ArgumentEncoder* MTL::Device::newArgumentEncoder(const NS::Array* arguments)
{
return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithArguments_), arguments);
}
_MTL_INLINE bool MTL::Device::supportsRasterizationRateMap(NS::UInteger layerCount)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRasterizationRateMapWithLayerCount_), layerCount);
}
_MTL_INLINE MTL::RasterizationRateMap* MTL::Device::newRasterizationRateMap(const MTL::RasterizationRateMapDescriptor* descriptor)
{
return Object::sendMessage<MTL::RasterizationRateMap*>(this, _MTL_PRIVATE_SEL(newRasterizationRateMapWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::IndirectCommandBuffer* MTL::Device::newIndirectCommandBuffer(const MTL::IndirectCommandBufferDescriptor* descriptor, NS::UInteger maxCount, MTL::ResourceOptions options)
{
return Object::sendMessage<MTL::IndirectCommandBuffer*>(this, _MTL_PRIVATE_SEL(newIndirectCommandBufferWithDescriptor_maxCommandCount_options_), descriptor, maxCount, options);
}
_MTL_INLINE MTL::Event* MTL::Device::newEvent()
{
return Object::sendMessage<MTL::Event*>(this, _MTL_PRIVATE_SEL(newEvent));
}
_MTL_INLINE MTL::SharedEvent* MTL::Device::newSharedEvent()
{
return Object::sendMessage<MTL::SharedEvent*>(this, _MTL_PRIVATE_SEL(newSharedEvent));
}
_MTL_INLINE MTL::SharedEvent* MTL::Device::newSharedEvent(const MTL::SharedEventHandle* sharedEventHandle)
{
return Object::sendMessage<MTL::SharedEvent*>(this, _MTL_PRIVATE_SEL(newSharedEventWithHandle_), sharedEventHandle);
}
_MTL_INLINE uint64_t MTL::Device::peerGroupID() const
{
return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(peerGroupID));
}
_MTL_INLINE uint32_t MTL::Device::peerIndex() const
{
return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(peerIndex));
}
_MTL_INLINE uint32_t MTL::Device::peerCount() const
{
return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(peerCount));
}
_MTL_INLINE MTL::Size MTL::Device::sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount)
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_), textureType, pixelFormat, sampleCount);
}
_MTL_INLINE NS::UInteger MTL::Device::sparseTileSizeInBytes() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sparseTileSizeInBytes));
}
_MTL_INLINE void MTL::Device::convertSparsePixelRegions(const MTL::Region* pixelRegions, MTL::Region* tileRegions, MTL::Size tileSize, MTL::SparseTextureRegionAlignmentMode mode, NS::UInteger numRegions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(convertSparsePixelRegions_toTileRegions_withTileSize_alignmentMode_numRegions_), pixelRegions, tileRegions, tileSize, mode, numRegions);
}
_MTL_INLINE void MTL::Device::convertSparseTileRegions(const MTL::Region* tileRegions, MTL::Region* pixelRegions, MTL::Size tileSize, NS::UInteger numRegions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(convertSparseTileRegions_toPixelRegions_withTileSize_numRegions_), tileRegions, pixelRegions, tileSize, numRegions);
}
_MTL_INLINE NS::UInteger MTL::Device::maxBufferLength() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxBufferLength));
}
_MTL_INLINE NS::Array* MTL::Device::counterSets() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(counterSets));
}
_MTL_INLINE MTL::CounterSampleBuffer* MTL::Device::newCounterSampleBuffer(const MTL::CounterSampleBufferDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(newCounterSampleBufferWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE void MTL::Device::sampleTimestamps(MTL::Timestamp* cpuTimestamp, MTL::Timestamp* gpuTimestamp)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleTimestamps_gpuTimestamp_), cpuTimestamp, gpuTimestamp);
}
_MTL_INLINE bool MTL::Device::supportsCounterSampling(MTL::CounterSamplingPoint samplingPoint)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsCounterSampling_), samplingPoint);
}
_MTL_INLINE bool MTL::Device::supportsVertexAmplificationCount(NS::UInteger count)
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsVertexAmplificationCount_), count);
}
_MTL_INLINE bool MTL::Device::supportsDynamicLibraries() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsDynamicLibraries));
}
_MTL_INLINE bool MTL::Device::supportsRenderDynamicLibraries() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRenderDynamicLibraries));
}
_MTL_INLINE MTL::DynamicLibrary* MTL::Device::newDynamicLibrary(const MTL::Library* library, NS::Error** error)
{
return Object::sendMessage<MTL::DynamicLibrary*>(this, _MTL_PRIVATE_SEL(newDynamicLibrary_error_), library, error);
}
_MTL_INLINE MTL::DynamicLibrary* MTL::Device::newDynamicLibrary(const NS::URL* url, NS::Error** error)
{
return Object::sendMessage<MTL::DynamicLibrary*>(this, _MTL_PRIVATE_SEL(newDynamicLibraryWithURL_error_), url, error);
}
_MTL_INLINE MTL::BinaryArchive* MTL::Device::newBinaryArchive(const MTL::BinaryArchiveDescriptor* descriptor, NS::Error** error)
{
return Object::sendMessage<MTL::BinaryArchive*>(this, _MTL_PRIVATE_SEL(newBinaryArchiveWithDescriptor_error_), descriptor, error);
}
_MTL_INLINE bool MTL::Device::supportsRaytracing() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRaytracing));
}
_MTL_INLINE MTL::AccelerationStructureSizes MTL::Device::accelerationStructureSizes(const MTL::AccelerationStructureDescriptor* descriptor)
{
return Object::sendMessage<MTL::AccelerationStructureSizes>(this, _MTL_PRIVATE_SEL(accelerationStructureSizesWithDescriptor_), descriptor);
}
_MTL_INLINE MTL::AccelerationStructure* MTL::Device::newAccelerationStructure(NS::UInteger size)
{
return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithSize_), size);
}
_MTL_INLINE MTL::AccelerationStructure* MTL::Device::newAccelerationStructure(const MTL::AccelerationStructureDescriptor* descriptor)
{
return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithDescriptor_), descriptor);
}
_MTL_INLINE bool MTL::Device::supportsFunctionPointers() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFunctionPointers));
}
_MTL_INLINE bool MTL::Device::supportsFunctionPointersFromRender() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFunctionPointersFromRender));
}
_MTL_INLINE bool MTL::Device::supportsRaytracingFromRender() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRaytracingFromRender));
}
_MTL_INLINE bool MTL::Device::supportsPrimitiveMotionBlur() const
{
return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsPrimitiveMotionBlur));
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, DynamicLibraryError) {
DynamicLibraryErrorNone = 0,
DynamicLibraryErrorInvalidFile = 1,
DynamicLibraryErrorCompilationFailure = 2,
DynamicLibraryErrorUnresolvedInstallName = 3,
DynamicLibraryErrorDependencyLoadFailure = 4,
DynamicLibraryErrorUnsupported = 5,
};
class DynamicLibrary : public NS::Referencing<DynamicLibrary>
{
public:
NS::String* label() const;
void setLabel(const NS::String* label);
class Device* device() const;
NS::String* installName() const;
bool serializeToURL(const NS::URL* url, NS::Error** error);
};
}
_MTL_INLINE NS::String* MTL::DynamicLibrary::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::DynamicLibrary::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::Device* MTL::DynamicLibrary::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::DynamicLibrary::installName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName));
}
_MTL_INLINE bool MTL::DynamicLibrary::serializeToURL(const NS::URL* url, NS::Error** error)
{
return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(serializeToURL_error_), url, error);
}
#pragma once
namespace MTL
{
class Event : public NS::Referencing<Event>
{
public:
class Device* device() const;
NS::String* label() const;
void setLabel(const NS::String* label);
};
class SharedEventListener : public NS::Referencing<SharedEventListener>
{
public:
static class SharedEventListener* alloc();
MTL::SharedEventListener* init();
MTL::SharedEventListener* init(const dispatch_queue_t dispatchQueue);
dispatch_queue_t dispatchQueue() const;
};
using SharedEventNotificationBlock = void (^)(SharedEvent* pEvent, std::uint64_t value);
class SharedEvent : public NS::Referencing<SharedEvent, Event>
{
public:
void notifyListener(const class SharedEventListener* listener, uint64_t value, const MTL::SharedEventNotificationBlock block);
class SharedEventHandle* newSharedEventHandle();
uint64_t signaledValue() const;
void setSignaledValue(uint64_t signaledValue);
};
class SharedEventHandle : public NS::Referencing<SharedEventHandle>
{
public:
static class SharedEventHandle* alloc();
class SharedEventHandle* init();
NS::String* label() const;
};
struct SharedEventHandlePrivate
{
} _MTL_PACKED;
}
_MTL_INLINE MTL::Device* MTL::Event::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::Event::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Event::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::alloc()
{
return NS::Object::alloc<MTL::SharedEventListener>(_MTL_PRIVATE_CLS(MTLSharedEventListener));
}
_MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::init()
{
return NS::Object::init<MTL::SharedEventListener>();
}
_MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::init(const dispatch_queue_t dispatchQueue)
{
return Object::sendMessage<MTL::SharedEventListener*>(this, _MTL_PRIVATE_SEL(initWithDispatchQueue_), dispatchQueue);
}
_MTL_INLINE dispatch_queue_t MTL::SharedEventListener::dispatchQueue() const
{
return Object::sendMessage<dispatch_queue_t>(this, _MTL_PRIVATE_SEL(dispatchQueue));
}
_MTL_INLINE void MTL::SharedEvent::notifyListener(const MTL::SharedEventListener* listener, uint64_t value, const MTL::SharedEventNotificationBlock block)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(notifyListener_atValue_block_), listener, value, block);
}
_MTL_INLINE MTL::SharedEventHandle* MTL::SharedEvent::newSharedEventHandle()
{
return Object::sendMessage<MTL::SharedEventHandle*>(this, _MTL_PRIVATE_SEL(newSharedEventHandle));
}
_MTL_INLINE uint64_t MTL::SharedEvent::signaledValue() const
{
return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(signaledValue));
}
_MTL_INLINE void MTL::SharedEvent::setSignaledValue(uint64_t signaledValue)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSignaledValue_), signaledValue);
}
_MTL_INLINE MTL::SharedEventHandle* MTL::SharedEventHandle::alloc()
{
return NS::Object::alloc<MTL::SharedEventHandle>(_MTL_PRIVATE_CLS(MTLSharedEventHandle));
}
_MTL_INLINE MTL::SharedEventHandle* MTL::SharedEventHandle::init()
{
return NS::Object::init<MTL::SharedEventHandle>();
}
_MTL_INLINE NS::String* MTL::SharedEventHandle::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
#pragma once
namespace MTL
{
class Fence : public NS::Referencing<Fence>
{
public:
class Device* device() const;
NS::String* label() const;
void setLabel(const NS::String* label);
};
}
_MTL_INLINE MTL::Device* MTL::Fence::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::Fence::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::Fence::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
#pragma once
namespace MTL
{
class FunctionConstantValues : public NS::Copying<FunctionConstantValues>
{
public:
static class FunctionConstantValues* alloc();
class FunctionConstantValues* init();
void setConstantValue(const void* value, MTL::DataType type, NS::UInteger index);
void setConstantValues(const void* values, MTL::DataType type, NS::Range range);
void setConstantValue(const void* value, MTL::DataType type, const NS::String* name);
void reset();
};
}
_MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionConstantValues::alloc()
{
return NS::Object::alloc<MTL::FunctionConstantValues>(_MTL_PRIVATE_CLS(MTLFunctionConstantValues));
}
_MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionConstantValues::init()
{
return NS::Object::init<MTL::FunctionConstantValues>();
}
_MTL_INLINE void MTL::FunctionConstantValues::setConstantValue(const void* value, MTL::DataType type, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValue_type_atIndex_), value, type, index);
}
_MTL_INLINE void MTL::FunctionConstantValues::setConstantValues(const void* values, MTL::DataType type, NS::Range range)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValues_type_withRange_), values, type, range);
}
_MTL_INLINE void MTL::FunctionConstantValues::setConstantValue(const void* value, MTL::DataType type, const NS::String* name)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValue_type_withName_), value, type, name);
}
_MTL_INLINE void MTL::FunctionConstantValues::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, FunctionLogType) {
FunctionLogTypeValidation = 0,
};
class LogContainer : public NS::Referencing<LogContainer, NS::FastEnumeration>
{
public:
};
class FunctionLogDebugLocation : public NS::Referencing<FunctionLogDebugLocation>
{
public:
NS::String* functionName() const;
NS::URL* URL() const;
NS::UInteger line() const;
NS::UInteger column() const;
};
class FunctionLog : public NS::Referencing<FunctionLog>
{
public:
MTL::FunctionLogType type() const;
NS::String* encoderLabel() const;
class Function* function() const;
class FunctionLogDebugLocation* debugLocation() const;
};
}
_MTL_INLINE NS::String* MTL::FunctionLogDebugLocation::functionName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(functionName));
}
_MTL_INLINE NS::URL* MTL::FunctionLogDebugLocation::URL() const
{
return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(URL));
}
_MTL_INLINE NS::UInteger MTL::FunctionLogDebugLocation::line() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(line));
}
_MTL_INLINE NS::UInteger MTL::FunctionLogDebugLocation::column() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(column));
}
_MTL_INLINE MTL::FunctionLogType MTL::FunctionLog::type() const
{
return Object::sendMessage<MTL::FunctionLogType>(this, _MTL_PRIVATE_SEL(type));
}
_MTL_INLINE NS::String* MTL::FunctionLog::encoderLabel() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(encoderLabel));
}
_MTL_INLINE MTL::Function* MTL::FunctionLog::function() const
{
return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(function));
}
_MTL_INLINE MTL::FunctionLogDebugLocation* MTL::FunctionLog::debugLocation() const
{
return Object::sendMessage<MTL::FunctionLogDebugLocation*>(this, _MTL_PRIVATE_SEL(debugLocation));
}
#pragma once
namespace MTL
{
class FunctionStitchingAttribute : public NS::Referencing<FunctionStitchingAttribute>
{
};
class FunctionStitchingAttributeAlwaysInline : public NS::Referencing<FunctionStitchingAttributeAlwaysInline, FunctionStitchingAttribute>
{
public:
static class FunctionStitchingAttributeAlwaysInline* alloc();
class FunctionStitchingAttributeAlwaysInline* init();
};
class FunctionStitchingNode : public NS::Copying<FunctionStitchingNode>
{
};
class FunctionStitchingInputNode : public NS::Referencing<FunctionStitchingInputNode, FunctionStitchingNode>
{
public:
static class FunctionStitchingInputNode* alloc();
class FunctionStitchingInputNode* init();
NS::UInteger argumentIndex() const;
void setArgumentIndex(NS::UInteger argumentIndex);
MTL::FunctionStitchingInputNode* init(NS::UInteger argument);
};
class FunctionStitchingFunctionNode : public NS::Referencing<FunctionStitchingFunctionNode, FunctionStitchingNode>
{
public:
static class FunctionStitchingFunctionNode* alloc();
class FunctionStitchingFunctionNode* init();
NS::String* name() const;
void setName(const NS::String* name);
NS::Array* arguments() const;
void setArguments(const NS::Array* arguments);
NS::Array* controlDependencies() const;
void setControlDependencies(const NS::Array* controlDependencies);
MTL::FunctionStitchingFunctionNode* init(const NS::String* name, const NS::Array* arguments, const NS::Array* controlDependencies);
};
class FunctionStitchingGraph : public NS::Copying<FunctionStitchingGraph>
{
public:
static class FunctionStitchingGraph* alloc();
class FunctionStitchingGraph* init();
NS::String* functionName() const;
void setFunctionName(const NS::String* functionName);
NS::Array* nodes() const;
void setNodes(const NS::Array* nodes);
class FunctionStitchingFunctionNode* outputNode() const;
void setOutputNode(const class FunctionStitchingFunctionNode* outputNode);
NS::Array* attributes() const;
void setAttributes(const NS::Array* attributes);
MTL::FunctionStitchingGraph* init(const NS::String* functionName, const NS::Array* nodes, const class FunctionStitchingFunctionNode* outputNode, const NS::Array* attributes);
};
class StitchedLibraryDescriptor : public NS::Copying<StitchedLibraryDescriptor>
{
public:
static class StitchedLibraryDescriptor* alloc();
class StitchedLibraryDescriptor* init();
NS::Array* functionGraphs() const;
void setFunctionGraphs(const NS::Array* functionGraphs);
NS::Array* functions() const;
void setFunctions(const NS::Array* functions);
};
}
_MTL_INLINE MTL::FunctionStitchingAttributeAlwaysInline* MTL::FunctionStitchingAttributeAlwaysInline::alloc()
{
return NS::Object::alloc<MTL::FunctionStitchingAttributeAlwaysInline>(_MTL_PRIVATE_CLS(MTLFunctionStitchingAttributeAlwaysInline));
}
_MTL_INLINE MTL::FunctionStitchingAttributeAlwaysInline* MTL::FunctionStitchingAttributeAlwaysInline::init()
{
return NS::Object::init<MTL::FunctionStitchingAttributeAlwaysInline>();
}
_MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::alloc()
{
return NS::Object::alloc<MTL::FunctionStitchingInputNode>(_MTL_PRIVATE_CLS(MTLFunctionStitchingInputNode));
}
_MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::init()
{
return NS::Object::init<MTL::FunctionStitchingInputNode>();
}
_MTL_INLINE NS::UInteger MTL::FunctionStitchingInputNode::argumentIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndex));
}
_MTL_INLINE void MTL::FunctionStitchingInputNode::setArgumentIndex(NS::UInteger argumentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentIndex_), argumentIndex);
}
_MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::init(NS::UInteger argument)
{
return Object::sendMessage<MTL::FunctionStitchingInputNode*>(this, _MTL_PRIVATE_SEL(initWithArgumentIndex_), argument);
}
_MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::alloc()
{
return NS::Object::alloc<MTL::FunctionStitchingFunctionNode>(_MTL_PRIVATE_CLS(MTLFunctionStitchingFunctionNode));
}
_MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::init()
{
return NS::Object::init<MTL::FunctionStitchingFunctionNode>();
}
_MTL_INLINE NS::String* MTL::FunctionStitchingFunctionNode::name() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name));
}
_MTL_INLINE void MTL::FunctionStitchingFunctionNode::setName(const NS::String* name)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setName_), name);
}
_MTL_INLINE NS::Array* MTL::FunctionStitchingFunctionNode::arguments() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(arguments));
}
_MTL_INLINE void MTL::FunctionStitchingFunctionNode::setArguments(const NS::Array* arguments)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArguments_), arguments);
}
_MTL_INLINE NS::Array* MTL::FunctionStitchingFunctionNode::controlDependencies() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(controlDependencies));
}
_MTL_INLINE void MTL::FunctionStitchingFunctionNode::setControlDependencies(const NS::Array* controlDependencies)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlDependencies_), controlDependencies);
}
_MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::init(const NS::String* name, const NS::Array* arguments, const NS::Array* controlDependencies)
{
return Object::sendMessage<MTL::FunctionStitchingFunctionNode*>(this, _MTL_PRIVATE_SEL(initWithName_arguments_controlDependencies_), name, arguments, controlDependencies);
}
_MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::alloc()
{
return NS::Object::alloc<MTL::FunctionStitchingGraph>(_MTL_PRIVATE_CLS(MTLFunctionStitchingGraph));
}
_MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::init()
{
return NS::Object::init<MTL::FunctionStitchingGraph>();
}
_MTL_INLINE NS::String* MTL::FunctionStitchingGraph::functionName() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(functionName));
}
_MTL_INLINE void MTL::FunctionStitchingGraph::setFunctionName(const NS::String* functionName)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionName_), functionName);
}
_MTL_INLINE NS::Array* MTL::FunctionStitchingGraph::nodes() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(nodes));
}
_MTL_INLINE void MTL::FunctionStitchingGraph::setNodes(const NS::Array* nodes)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setNodes_), nodes);
}
_MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingGraph::outputNode() const
{
return Object::sendMessage<MTL::FunctionStitchingFunctionNode*>(this, _MTL_PRIVATE_SEL(outputNode));
}
_MTL_INLINE void MTL::FunctionStitchingGraph::setOutputNode(const MTL::FunctionStitchingFunctionNode* outputNode)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOutputNode_), outputNode);
}
_MTL_INLINE NS::Array* MTL::FunctionStitchingGraph::attributes() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(attributes));
}
_MTL_INLINE void MTL::FunctionStitchingGraph::setAttributes(const NS::Array* attributes)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAttributes_), attributes);
}
_MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::init(const NS::String* functionName, const NS::Array* nodes, const MTL::FunctionStitchingFunctionNode* outputNode, const NS::Array* attributes)
{
return Object::sendMessage<MTL::FunctionStitchingGraph*>(this, _MTL_PRIVATE_SEL(initWithFunctionName_nodes_outputNode_attributes_), functionName, nodes, outputNode, attributes);
}
_MTL_INLINE MTL::StitchedLibraryDescriptor* MTL::StitchedLibraryDescriptor::alloc()
{
return NS::Object::alloc<MTL::StitchedLibraryDescriptor>(_MTL_PRIVATE_CLS(MTLStitchedLibraryDescriptor));
}
_MTL_INLINE MTL::StitchedLibraryDescriptor* MTL::StitchedLibraryDescriptor::init()
{
return NS::Object::init<MTL::StitchedLibraryDescriptor>();
}
_MTL_INLINE NS::Array* MTL::StitchedLibraryDescriptor::functionGraphs() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functionGraphs));
}
_MTL_INLINE void MTL::StitchedLibraryDescriptor::setFunctionGraphs(const NS::Array* functionGraphs)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionGraphs_), functionGraphs);
}
_MTL_INLINE NS::Array* MTL::StitchedLibraryDescriptor::functions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functions));
}
_MTL_INLINE void MTL::StitchedLibraryDescriptor::setFunctions(const NS::Array* functions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_), functions);
}
#pragma once
namespace MTL
{
class IndirectRenderCommand : public NS::Referencing<IndirectRenderCommand>
{
public:
void setRenderPipelineState(const class RenderPipelineState* pipelineState);
void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void setFragmentBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride);
void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride);
void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance);
void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance);
void reset();
};
class IndirectComputeCommand : public NS::Referencing<IndirectComputeCommand>
{
public:
void setComputePipelineState(const class ComputePipelineState* pipelineState);
void setKernelBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index);
void concurrentDispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup);
void concurrentDispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup);
void setBarrier();
void clearBarrier();
void setImageblockWidth(NS::UInteger width, NS::UInteger height);
void reset();
void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index);
void setStageInRegion(MTL::Region region);
};
}
_MTL_INLINE void MTL::IndirectRenderCommand::setRenderPipelineState(const MTL::RenderPipelineState* pipelineState)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_), pipelineState);
}
_MTL_INLINE void MTL::IndirectRenderCommand::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::IndirectRenderCommand::setFragmentBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::IndirectRenderCommand::drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, instanceCount, baseInstance, buffer, offset, instanceStride);
}
_MTL_INLINE void MTL::IndirectRenderCommand::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, instanceCount, baseInstance, buffer, offset, instanceStride);
}
_MTL_INLINE void MTL::IndirectRenderCommand::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_), primitiveType, vertexStart, vertexCount, instanceCount, baseInstance);
}
_MTL_INLINE void MTL::IndirectRenderCommand::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount, baseVertex, baseInstance);
}
_MTL_INLINE void MTL::IndirectRenderCommand::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
_MTL_INLINE void MTL::IndirectComputeCommand::setComputePipelineState(const MTL::ComputePipelineState* pipelineState)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_), pipelineState);
}
_MTL_INLINE void MTL::IndirectComputeCommand::setKernelBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setKernelBuffer_offset_atIndex_), buffer, offset, index);
}
_MTL_INLINE void MTL::IndirectComputeCommand::concurrentDispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(concurrentDispatchThreadgroups_threadsPerThreadgroup_), threadgroupsPerGrid, threadsPerThreadgroup);
}
_MTL_INLINE void MTL::IndirectComputeCommand::concurrentDispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(concurrentDispatchThreads_threadsPerThreadgroup_), threadsPerGrid, threadsPerThreadgroup);
}
_MTL_INLINE void MTL::IndirectComputeCommand::setBarrier()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBarrier));
}
_MTL_INLINE void MTL::IndirectComputeCommand::clearBarrier()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(clearBarrier));
}
_MTL_INLINE void MTL::IndirectComputeCommand::setImageblockWidth(NS::UInteger width, NS::UInteger height)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockWidth_height_), width, height);
}
_MTL_INLINE void MTL::IndirectComputeCommand::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
_MTL_INLINE void MTL::IndirectComputeCommand::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_atIndex_), length, index);
}
_MTL_INLINE void MTL::IndirectComputeCommand::setStageInRegion(MTL::Region region)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegion_), region);
}
#pragma once
namespace MTL
{
class LinkedFunctions : public NS::Copying<LinkedFunctions>
{
public:
static class LinkedFunctions* alloc();
class LinkedFunctions* init();
static class LinkedFunctions* linkedFunctions();
NS::Array* functions() const;
void setFunctions(const NS::Array* functions);
NS::Array* binaryFunctions() const;
void setBinaryFunctions(const NS::Array* binaryFunctions);
NS::Array* groups() const;
void setGroups(const NS::Array* groups);
NS::Array* privateFunctions() const;
void setPrivateFunctions(const NS::Array* privateFunctions);
};
}
_MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::alloc()
{
return NS::Object::alloc<MTL::LinkedFunctions>(_MTL_PRIVATE_CLS(MTLLinkedFunctions));
}
_MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::init()
{
return NS::Object::init<MTL::LinkedFunctions>();
}
_MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::linkedFunctions()
{
return Object::sendMessage<MTL::LinkedFunctions*>(_MTL_PRIVATE_CLS(MTLLinkedFunctions), _MTL_PRIVATE_SEL(linkedFunctions));
}
_MTL_INLINE NS::Array* MTL::LinkedFunctions::functions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functions));
}
_MTL_INLINE void MTL::LinkedFunctions::setFunctions(const NS::Array* functions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_), functions);
}
_MTL_INLINE NS::Array* MTL::LinkedFunctions::binaryFunctions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryFunctions));
}
_MTL_INLINE void MTL::LinkedFunctions::setBinaryFunctions(const NS::Array* binaryFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryFunctions_), binaryFunctions);
}
_MTL_INLINE NS::Array* MTL::LinkedFunctions::groups() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(groups));
}
_MTL_INLINE void MTL::LinkedFunctions::setGroups(const NS::Array* groups)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setGroups_), groups);
}
_MTL_INLINE NS::Array* MTL::LinkedFunctions::privateFunctions() const
{
return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(privateFunctions));
}
_MTL_INLINE void MTL::LinkedFunctions::setPrivateFunctions(const NS::Array* privateFunctions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrivateFunctions_), privateFunctions);
}
#pragma once
namespace MTL
{
class ParallelRenderCommandEncoder : public NS::Referencing<ParallelRenderCommandEncoder, CommandEncoder>
{
public:
class RenderCommandEncoder* renderCommandEncoder();
void setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex);
void setDepthStoreAction(MTL::StoreAction storeAction);
void setStencilStoreAction(MTL::StoreAction storeAction);
void setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex);
void setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions);
void setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions);
};
}
_MTL_INLINE MTL::RenderCommandEncoder* MTL::ParallelRenderCommandEncoder::renderCommandEncoder()
{
return Object::sendMessage<MTL::RenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(renderCommandEncoder));
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreAction_atIndex_), storeAction, colorAttachmentIndex);
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setDepthStoreAction(MTL::StoreAction storeAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreAction_), storeAction);
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setStencilStoreAction(MTL::StoreAction storeAction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreAction_), storeAction);
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreActionOptions_atIndex_), storeActionOptions, colorAttachmentIndex);
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreActionOptions_), storeActionOptions);
}
_MTL_INLINE void MTL::ParallelRenderCommandEncoder::setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreActionOptions_), storeActionOptions);
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, Mutability) {
MutabilityDefault = 0,
MutabilityMutable = 1,
MutabilityImmutable = 2,
};
class PipelineBufferDescriptor : public NS::Copying<PipelineBufferDescriptor>
{
public:
static class PipelineBufferDescriptor* alloc();
class PipelineBufferDescriptor* init();
MTL::Mutability mutability() const;
void setMutability(MTL::Mutability mutability);
};
class PipelineBufferDescriptorArray : public NS::Referencing<PipelineBufferDescriptorArray>
{
public:
static class PipelineBufferDescriptorArray* alloc();
class PipelineBufferDescriptorArray* init();
class PipelineBufferDescriptor* object(NS::UInteger bufferIndex);
void setObject(const class PipelineBufferDescriptor* buffer, NS::UInteger bufferIndex);
};
}
_MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptor::alloc()
{
return NS::Object::alloc<MTL::PipelineBufferDescriptor>(_MTL_PRIVATE_CLS(MTLPipelineBufferDescriptor));
}
_MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptor::init()
{
return NS::Object::init<MTL::PipelineBufferDescriptor>();
}
_MTL_INLINE MTL::Mutability MTL::PipelineBufferDescriptor::mutability() const
{
return Object::sendMessage<MTL::Mutability>(this, _MTL_PRIVATE_SEL(mutability));
}
_MTL_INLINE void MTL::PipelineBufferDescriptor::setMutability(MTL::Mutability mutability)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMutability_), mutability);
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::PipelineBufferDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::PipelineBufferDescriptorArray>(_MTL_PRIVATE_CLS(MTLPipelineBufferDescriptorArray));
}
_MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::PipelineBufferDescriptorArray::init()
{
return NS::Object::init<MTL::PipelineBufferDescriptorArray>();
}
_MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptorArray::object(NS::UInteger bufferIndex)
{
return Object::sendMessage<MTL::PipelineBufferDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), bufferIndex);
}
_MTL_INLINE void MTL::PipelineBufferDescriptorArray::setObject(const MTL::PipelineBufferDescriptor* buffer, NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), buffer, bufferIndex);
}
#pragma once
namespace MTL
{
class RasterizationRateSampleArray : public NS::Referencing<RasterizationRateSampleArray>
{
public:
static class RasterizationRateSampleArray* alloc();
class RasterizationRateSampleArray* init();
NS::Number* object(NS::UInteger index);
void setObject(const NS::Number* value, NS::UInteger index);
};
class RasterizationRateLayerDescriptor : public NS::Copying<RasterizationRateLayerDescriptor>
{
public:
static class RasterizationRateLayerDescriptor* alloc();
MTL::RasterizationRateLayerDescriptor* init();
MTL::RasterizationRateLayerDescriptor* init(MTL::Size sampleCount);
MTL::RasterizationRateLayerDescriptor* init(MTL::Size sampleCount, const float* horizontal, const float* vertical);
MTL::Size sampleCount() const;
MTL::Size maxSampleCount() const;
float* horizontalSampleStorage() const;
float* verticalSampleStorage() const;
class RasterizationRateSampleArray* horizontal() const;
class RasterizationRateSampleArray* vertical() const;
void setSampleCount(MTL::Size sampleCount);
};
class RasterizationRateLayerArray : public NS::Referencing<RasterizationRateLayerArray>
{
public:
static class RasterizationRateLayerArray* alloc();
class RasterizationRateLayerArray* init();
class RasterizationRateLayerDescriptor* object(NS::UInteger layerIndex);
void setObject(const class RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex);
};
class RasterizationRateMapDescriptor : public NS::Copying<RasterizationRateMapDescriptor>
{
public:
static class RasterizationRateMapDescriptor* alloc();
class RasterizationRateMapDescriptor* init();
static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize);
static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize, const class RasterizationRateLayerDescriptor* layer);
static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize, NS::UInteger layerCount, MTL::RasterizationRateLayerDescriptor* const* layers);
class RasterizationRateLayerDescriptor* layer(NS::UInteger layerIndex);
void setLayer(const class RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex);
class RasterizationRateLayerArray* layers() const;
MTL::Size screenSize() const;
void setScreenSize(MTL::Size screenSize);
NS::String* label() const;
void setLabel(const NS::String* label);
NS::UInteger layerCount() const;
};
class RasterizationRateMap : public NS::Referencing<RasterizationRateMap>
{
public:
class Device* device() const;
NS::String* label() const;
MTL::Size screenSize() const;
MTL::Size physicalGranularity() const;
NS::UInteger layerCount() const;
MTL::SizeAndAlign parameterBufferSizeAndAlign() const;
void copyParameterDataToBuffer(const class Buffer* buffer, NS::UInteger offset);
MTL::Size physicalSize(NS::UInteger layerIndex);
MTL::Coordinate2D mapScreenToPhysicalCoordinates(MTL::Coordinate2D screenCoordinates, NS::UInteger layerIndex);
MTL::Coordinate2D mapPhysicalToScreenCoordinates(MTL::Coordinate2D physicalCoordinates, NS::UInteger layerIndex);
};
}
_MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateSampleArray::alloc()
{
return NS::Object::alloc<MTL::RasterizationRateSampleArray>(_MTL_PRIVATE_CLS(MTLRasterizationRateSampleArray));
}
_MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateSampleArray::init()
{
return NS::Object::init<MTL::RasterizationRateSampleArray>();
}
_MTL_INLINE NS::Number* MTL::RasterizationRateSampleArray::object(NS::UInteger index)
{
return Object::sendMessage<NS::Number*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index);
}
_MTL_INLINE void MTL::RasterizationRateSampleArray::setObject(const NS::Number* value, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), value, index);
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::alloc()
{
return NS::Object::alloc<MTL::RasterizationRateLayerDescriptor>(_MTL_PRIVATE_CLS(MTLRasterizationRateLayerDescriptor));
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init()
{
return NS::Object::init<MTL::RasterizationRateLayerDescriptor>();
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init(MTL::Size sampleCount)
{
return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(initWithSampleCount_), sampleCount);
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init(MTL::Size sampleCount, const float* horizontal, const float* vertical)
{
return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(initWithSampleCount_horizontal_vertical_), sampleCount, horizontal, vertical);
}
_MTL_INLINE MTL::Size MTL::RasterizationRateLayerDescriptor::sampleCount() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(sampleCount));
}
_MTL_INLINE MTL::Size MTL::RasterizationRateLayerDescriptor::maxSampleCount() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(maxSampleCount));
}
_MTL_INLINE float* MTL::RasterizationRateLayerDescriptor::horizontalSampleStorage() const
{
return Object::sendMessage<float*>(this, _MTL_PRIVATE_SEL(horizontalSampleStorage));
}
_MTL_INLINE float* MTL::RasterizationRateLayerDescriptor::verticalSampleStorage() const
{
return Object::sendMessage<float*>(this, _MTL_PRIVATE_SEL(verticalSampleStorage));
}
_MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateLayerDescriptor::horizontal() const
{
return Object::sendMessage<MTL::RasterizationRateSampleArray*>(this, _MTL_PRIVATE_SEL(horizontal));
}
_MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateLayerDescriptor::vertical() const
{
return Object::sendMessage<MTL::RasterizationRateSampleArray*>(this, _MTL_PRIVATE_SEL(vertical));
}
_MTL_INLINE void MTL::RasterizationRateLayerDescriptor::setSampleCount(MTL::Size sampleCount)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount);
}
_MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateLayerArray::alloc()
{
return NS::Object::alloc<MTL::RasterizationRateLayerArray>(_MTL_PRIVATE_CLS(MTLRasterizationRateLayerArray));
}
_MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateLayerArray::init()
{
return NS::Object::init<MTL::RasterizationRateLayerArray>();
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerArray::object(NS::UInteger layerIndex)
{
return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), layerIndex);
}
_MTL_INLINE void MTL::RasterizationRateLayerArray::setObject(const MTL::RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), layer, layerIndex);
}
_MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::alloc()
{
return NS::Object::alloc<MTL::RasterizationRateMapDescriptor>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor));
}
_MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::init()
{
return NS::Object::init<MTL::RasterizationRateMapDescriptor>();
}
_MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize)
{
return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_), screenSize);
}
_MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize, const MTL::RasterizationRateLayerDescriptor* layer)
{
return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_layer_), screenSize, layer);
}
_MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize, NS::UInteger layerCount, MTL::RasterizationRateLayerDescriptor* const* layers)
{
return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_layerCount_layers_), screenSize, layerCount, layers);
}
_MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateMapDescriptor::layer(NS::UInteger layerIndex)
{
return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(layerAtIndex_), layerIndex);
}
_MTL_INLINE void MTL::RasterizationRateMapDescriptor::setLayer(const MTL::RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLayer_atIndex_), layer, layerIndex);
}
_MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateMapDescriptor::layers() const
{
return Object::sendMessage<MTL::RasterizationRateLayerArray*>(this, _MTL_PRIVATE_SEL(layers));
}
_MTL_INLINE MTL::Size MTL::RasterizationRateMapDescriptor::screenSize() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(screenSize));
}
_MTL_INLINE void MTL::RasterizationRateMapDescriptor::setScreenSize(MTL::Size screenSize)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScreenSize_), screenSize);
}
_MTL_INLINE NS::String* MTL::RasterizationRateMapDescriptor::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE void MTL::RasterizationRateMapDescriptor::setLabel(const NS::String* label)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label);
}
_MTL_INLINE NS::UInteger MTL::RasterizationRateMapDescriptor::layerCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(layerCount));
}
_MTL_INLINE MTL::Device* MTL::RasterizationRateMap::device() const
{
return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device));
}
_MTL_INLINE NS::String* MTL::RasterizationRateMap::label() const
{
return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label));
}
_MTL_INLINE MTL::Size MTL::RasterizationRateMap::screenSize() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(screenSize));
}
_MTL_INLINE MTL::Size MTL::RasterizationRateMap::physicalGranularity() const
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(physicalGranularity));
}
_MTL_INLINE NS::UInteger MTL::RasterizationRateMap::layerCount() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(layerCount));
}
_MTL_INLINE MTL::SizeAndAlign MTL::RasterizationRateMap::parameterBufferSizeAndAlign() const
{
return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(parameterBufferSizeAndAlign));
}
_MTL_INLINE void MTL::RasterizationRateMap::copyParameterDataToBuffer(const MTL::Buffer* buffer, NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyParameterDataToBuffer_offset_), buffer, offset);
}
_MTL_INLINE MTL::Size MTL::RasterizationRateMap::physicalSize(NS::UInteger layerIndex)
{
return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(physicalSizeForLayer_), layerIndex);
}
_MTL_INLINE MTL::Coordinate2D MTL::RasterizationRateMap::mapScreenToPhysicalCoordinates(MTL::Coordinate2D screenCoordinates, NS::UInteger layerIndex)
{
return Object::sendMessage<MTL::Coordinate2D>(this, _MTL_PRIVATE_SEL(mapScreenToPhysicalCoordinates_forLayer_), screenCoordinates, layerIndex);
}
_MTL_INLINE MTL::Coordinate2D MTL::RasterizationRateMap::mapPhysicalToScreenCoordinates(MTL::Coordinate2D physicalCoordinates, NS::UInteger layerIndex)
{
return Object::sendMessage<MTL::Coordinate2D>(this, _MTL_PRIVATE_SEL(mapPhysicalToScreenCoordinates_forLayer_), physicalCoordinates, layerIndex);
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, SparseTextureMappingMode) {
SparseTextureMappingModeMap = 0,
SparseTextureMappingModeUnmap = 1,
};
struct MapIndirectArguments
{
uint32_t regionOriginX;
uint32_t regionOriginY;
uint32_t regionOriginZ;
uint32_t regionSizeWidth;
uint32_t regionSizeHeight;
uint32_t regionSizeDepth;
uint32_t mipMapLevel;
uint32_t sliceId;
} _MTL_PACKED;
class ResourceStateCommandEncoder : public NS::Referencing<ResourceStateCommandEncoder, CommandEncoder>
{
public:
void updateTextureMappings(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region* regions, const NS::UInteger* mipLevels, const NS::UInteger* slices, NS::UInteger numRegions);
void updateTextureMapping(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region region, const NS::UInteger mipLevel, const NS::UInteger slice);
void updateTextureMapping(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset);
void updateFence(const class Fence* fence);
void waitForFence(const class Fence* fence);
};
}
_MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMappings(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region* regions, const NS::UInteger* mipLevels, const NS::UInteger* slices, NS::UInteger numRegions)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMappings_mode_regions_mipLevels_slices_numRegions_), texture, mode, regions, mipLevels, slices, numRegions);
}
_MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMapping(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region region, const NS::UInteger mipLevel, const NS::UInteger slice)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMapping_mode_region_mipLevel_slice_), texture, mode, region, mipLevel, slice);
}
_MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMapping(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMapping_mode_indirectBuffer_indirectBufferOffset_), texture, mode, indirectBuffer, indirectBufferOffset);
}
_MTL_INLINE void MTL::ResourceStateCommandEncoder::updateFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence);
}
_MTL_INLINE void MTL::ResourceStateCommandEncoder::waitForFence(const MTL::Fence* fence)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence);
}
#pragma once
namespace MTL
{
class ResourceStatePassSampleBufferAttachmentDescriptor : public NS::Copying<ResourceStatePassSampleBufferAttachmentDescriptor>
{
public:
static class ResourceStatePassSampleBufferAttachmentDescriptor* alloc();
class ResourceStatePassSampleBufferAttachmentDescriptor* init();
class CounterSampleBuffer* sampleBuffer() const;
void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer);
NS::UInteger startOfEncoderSampleIndex() const;
void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex);
NS::UInteger endOfEncoderSampleIndex() const;
void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex);
};
class ResourceStatePassSampleBufferAttachmentDescriptorArray : public NS::Referencing<ResourceStatePassSampleBufferAttachmentDescriptorArray>
{
public:
static class ResourceStatePassSampleBufferAttachmentDescriptorArray* alloc();
class ResourceStatePassSampleBufferAttachmentDescriptorArray* init();
class ResourceStatePassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex);
void setObject(const class ResourceStatePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex);
};
class ResourceStatePassDescriptor : public NS::Copying<ResourceStatePassDescriptor>
{
public:
static class ResourceStatePassDescriptor* alloc();
class ResourceStatePassDescriptor* init();
static class ResourceStatePassDescriptor* resourceStatePassDescriptor();
class ResourceStatePassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const;
};
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::alloc()
{
return NS::Object::alloc<MTL::ResourceStatePassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptor));
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::init()
{
return NS::Object::init<MTL::ResourceStatePassSampleBufferAttachmentDescriptor>();
}
_MTL_INLINE MTL::CounterSampleBuffer* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::sampleBuffer() const
{
return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer));
}
_MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer);
}
_MTL_INLINE NS::UInteger MTL::ResourceStatePassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex);
}
_MTL_INLINE NS::UInteger MTL::ResourceStatePassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex));
}
_MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex);
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptorArray));
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::init()
{
return NS::Object::init<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray>();
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex)
{
return Object::sendMessage<MTL::ResourceStatePassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex);
}
_MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::setObject(const MTL::ResourceStatePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex);
}
_MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::alloc()
{
return NS::Object::alloc<MTL::ResourceStatePassDescriptor>(_MTL_PRIVATE_CLS(MTLResourceStatePassDescriptor));
}
_MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::init()
{
return NS::Object::init<MTL::ResourceStatePassDescriptor>();
}
_MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::resourceStatePassDescriptor()
{
return Object::sendMessage<MTL::ResourceStatePassDescriptor*>(_MTL_PRIVATE_CLS(MTLResourceStatePassDescriptor), _MTL_PRIVATE_SEL(resourceStatePassDescriptor));
}
_MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassDescriptor::sampleBufferAttachments() const
{
return Object::sendMessage<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments));
}
#pragma once
namespace MTL
{
_MTL_ENUM(NS::UInteger, VertexFormat) {
VertexFormatInvalid = 0,
VertexFormatUChar2 = 1,
VertexFormatUChar3 = 2,
VertexFormatUChar4 = 3,
VertexFormatChar2 = 4,
VertexFormatChar3 = 5,
VertexFormatChar4 = 6,
VertexFormatUChar2Normalized = 7,
VertexFormatUChar3Normalized = 8,
VertexFormatUChar4Normalized = 9,
VertexFormatChar2Normalized = 10,
VertexFormatChar3Normalized = 11,
VertexFormatChar4Normalized = 12,
VertexFormatUShort2 = 13,
VertexFormatUShort3 = 14,
VertexFormatUShort4 = 15,
VertexFormatShort2 = 16,
VertexFormatShort3 = 17,
VertexFormatShort4 = 18,
VertexFormatUShort2Normalized = 19,
VertexFormatUShort3Normalized = 20,
VertexFormatUShort4Normalized = 21,
VertexFormatShort2Normalized = 22,
VertexFormatShort3Normalized = 23,
VertexFormatShort4Normalized = 24,
VertexFormatHalf2 = 25,
VertexFormatHalf3 = 26,
VertexFormatHalf4 = 27,
VertexFormatFloat = 28,
VertexFormatFloat2 = 29,
VertexFormatFloat3 = 30,
VertexFormatFloat4 = 31,
VertexFormatInt = 32,
VertexFormatInt2 = 33,
VertexFormatInt3 = 34,
VertexFormatInt4 = 35,
VertexFormatUInt = 36,
VertexFormatUInt2 = 37,
VertexFormatUInt3 = 38,
VertexFormatUInt4 = 39,
VertexFormatInt1010102Normalized = 40,
VertexFormatUInt1010102Normalized = 41,
VertexFormatUChar4Normalized_BGRA = 42,
VertexFormatUChar = 45,
VertexFormatChar = 46,
VertexFormatUCharNormalized = 47,
VertexFormatCharNormalized = 48,
VertexFormatUShort = 49,
VertexFormatShort = 50,
VertexFormatUShortNormalized = 51,
VertexFormatShortNormalized = 52,
VertexFormatHalf = 53,
};
_MTL_ENUM(NS::UInteger, VertexStepFunction) {
VertexStepFunctionConstant = 0,
VertexStepFunctionPerVertex = 1,
VertexStepFunctionPerInstance = 2,
VertexStepFunctionPerPatch = 3,
VertexStepFunctionPerPatchControlPoint = 4,
};
class VertexBufferLayoutDescriptor : public NS::Copying<VertexBufferLayoutDescriptor>
{
public:
static class VertexBufferLayoutDescriptor* alloc();
class VertexBufferLayoutDescriptor* init();
NS::UInteger stride() const;
void setStride(NS::UInteger stride);
MTL::VertexStepFunction stepFunction() const;
void setStepFunction(MTL::VertexStepFunction stepFunction);
NS::UInteger stepRate() const;
void setStepRate(NS::UInteger stepRate);
};
class VertexBufferLayoutDescriptorArray : public NS::Referencing<VertexBufferLayoutDescriptorArray>
{
public:
static class VertexBufferLayoutDescriptorArray* alloc();
class VertexBufferLayoutDescriptorArray* init();
class VertexBufferLayoutDescriptor* object(NS::UInteger index);
void setObject(const class VertexBufferLayoutDescriptor* bufferDesc, NS::UInteger index);
};
class VertexAttributeDescriptor : public NS::Copying<VertexAttributeDescriptor>
{
public:
static class VertexAttributeDescriptor* alloc();
class VertexAttributeDescriptor* init();
MTL::VertexFormat format() const;
void setFormat(MTL::VertexFormat format);
NS::UInteger offset() const;
void setOffset(NS::UInteger offset);
NS::UInteger bufferIndex() const;
void setBufferIndex(NS::UInteger bufferIndex);
};
class VertexAttributeDescriptorArray : public NS::Referencing<VertexAttributeDescriptorArray>
{
public:
static class VertexAttributeDescriptorArray* alloc();
class VertexAttributeDescriptorArray* init();
class VertexAttributeDescriptor* object(NS::UInteger index);
void setObject(const class VertexAttributeDescriptor* attributeDesc, NS::UInteger index);
};
class VertexDescriptor : public NS::Copying<VertexDescriptor>
{
public:
static class VertexDescriptor* alloc();
class VertexDescriptor* init();
static class VertexDescriptor* vertexDescriptor();
class VertexBufferLayoutDescriptorArray* layouts() const;
class VertexAttributeDescriptorArray* attributes() const;
void reset();
};
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptor::alloc()
{
return NS::Object::alloc<MTL::VertexBufferLayoutDescriptor>(_MTL_PRIVATE_CLS(MTLVertexBufferLayoutDescriptor));
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptor::init()
{
return NS::Object::init<MTL::VertexBufferLayoutDescriptor>();
}
_MTL_INLINE NS::UInteger MTL::VertexBufferLayoutDescriptor::stride() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride));
}
_MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStride(NS::UInteger stride)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStride_), stride);
}
_MTL_INLINE MTL::VertexStepFunction MTL::VertexBufferLayoutDescriptor::stepFunction() const
{
return Object::sendMessage<MTL::VertexStepFunction>(this, _MTL_PRIVATE_SEL(stepFunction));
}
_MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStepFunction(MTL::VertexStepFunction stepFunction)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepFunction_), stepFunction);
}
_MTL_INLINE NS::UInteger MTL::VertexBufferLayoutDescriptor::stepRate() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stepRate));
}
_MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStepRate(NS::UInteger stepRate)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepRate_), stepRate);
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexBufferLayoutDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::VertexBufferLayoutDescriptorArray>(_MTL_PRIVATE_CLS(MTLVertexBufferLayoutDescriptorArray));
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexBufferLayoutDescriptorArray::init()
{
return NS::Object::init<MTL::VertexBufferLayoutDescriptorArray>();
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptorArray::object(NS::UInteger index)
{
return Object::sendMessage<MTL::VertexBufferLayoutDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index);
}
_MTL_INLINE void MTL::VertexBufferLayoutDescriptorArray::setObject(const MTL::VertexBufferLayoutDescriptor* bufferDesc, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), bufferDesc, index);
}
_MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptor::alloc()
{
return NS::Object::alloc<MTL::VertexAttributeDescriptor>(_MTL_PRIVATE_CLS(MTLVertexAttributeDescriptor));
}
_MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptor::init()
{
return NS::Object::init<MTL::VertexAttributeDescriptor>();
}
_MTL_INLINE MTL::VertexFormat MTL::VertexAttributeDescriptor::format() const
{
return Object::sendMessage<MTL::VertexFormat>(this, _MTL_PRIVATE_SEL(format));
}
_MTL_INLINE void MTL::VertexAttributeDescriptor::setFormat(MTL::VertexFormat format)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFormat_), format);
}
_MTL_INLINE NS::UInteger MTL::VertexAttributeDescriptor::offset() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset));
}
_MTL_INLINE void MTL::VertexAttributeDescriptor::setOffset(NS::UInteger offset)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset);
}
_MTL_INLINE NS::UInteger MTL::VertexAttributeDescriptor::bufferIndex() const
{
return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferIndex));
}
_MTL_INLINE void MTL::VertexAttributeDescriptor::setBufferIndex(NS::UInteger bufferIndex)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferIndex_), bufferIndex);
}
_MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexAttributeDescriptorArray::alloc()
{
return NS::Object::alloc<MTL::VertexAttributeDescriptorArray>(_MTL_PRIVATE_CLS(MTLVertexAttributeDescriptorArray));
}
_MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexAttributeDescriptorArray::init()
{
return NS::Object::init<MTL::VertexAttributeDescriptorArray>();
}
_MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptorArray::object(NS::UInteger index)
{
return Object::sendMessage<MTL::VertexAttributeDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index);
}
_MTL_INLINE void MTL::VertexAttributeDescriptorArray::setObject(const MTL::VertexAttributeDescriptor* attributeDesc, NS::UInteger index)
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attributeDesc, index);
}
_MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::alloc()
{
return NS::Object::alloc<MTL::VertexDescriptor>(_MTL_PRIVATE_CLS(MTLVertexDescriptor));
}
_MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::init()
{
return NS::Object::init<MTL::VertexDescriptor>();
}
_MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::vertexDescriptor()
{
return Object::sendMessage<MTL::VertexDescriptor*>(_MTL_PRIVATE_CLS(MTLVertexDescriptor), _MTL_PRIVATE_SEL(vertexDescriptor));
}
_MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexDescriptor::layouts() const
{
return Object::sendMessage<MTL::VertexBufferLayoutDescriptorArray*>(this, _MTL_PRIVATE_SEL(layouts));
}
_MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexDescriptor::attributes() const
{
return Object::sendMessage<MTL::VertexAttributeDescriptorArray*>(this, _MTL_PRIVATE_SEL(attributes));
}
_MTL_INLINE void MTL::VertexDescriptor::reset()
{
Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset));
}
| 39.162686 | 524 | 0.758276 | [
"object"
] |
ece4d45b5267634fa7609259fc0c0c5e21d47487 | 13,306 | h | C | Debugger/Debugger.h | ponymalt3/sl_processor | a8875a4345e24577d0df930ea83ff20f11e41590 | [
"MIT"
] | null | null | null | Debugger/Debugger.h | ponymalt3/sl_processor | a8875a4345e24577d0df930ea83ff20f11e41590 | [
"MIT"
] | null | null | null | Debugger/Debugger.h | ponymalt3/sl_processor | a8875a4345e24577d0df930ea83ff20f11e41590 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include <sstream>
#include <vector>
#include "SLProcessor.h"
#include "DebuggerInterface.h"
class Debugger
{
public:
Debugger(DebuggerInterface *interface,
const SymbolMap &globalSymbols,
const std::map<std::string,CodeGen::_FunctionInfo> &functionMap,
const std::map<uint32_t,uint32_t> &addrToLineMap,
const std::map<uint32_t,std::pair<std::string,uint32_t>> &lineToFileMap,
const std::map<std::string,std::vector<std::string>> &filesAsLineVector,
const uint16_t *code,
uint32_t codeSize,
uint32_t codeAddr)
: global_(globalSymbols)
{
interface_=interface;
functionMap_=functionMap;
addrToLineMap_=addrToLineMap;
lineToFileMap_=lineToFileMap;
filesAsLineVector_=filesAsLineVector;
code_=code;
codeSize_=codeSize;
codeAddr_=codeAddr;
for(auto &i : functionMap_)
{
addrToFunctionMap_.insert(std::make_pair(i.second.address_,i.first));
}
for(auto &i : addrToLineMap_)
{
lineToAddrMap_.insert(std::make_pair(i.second,i.first));
}
for(auto &i : lineToFileMap_)
{
fileToLineMap_.insert(std::make_pair(i.second.first,std::make_pair(i.first,i.second.second)));
}
callInfoValid_=false;
}
void loadCode()
{
interface_->writeCode(code_,codeSize_);
interface_->reset();
}
std::string command(const std::string &command)
{
if(command.substr(0,9) == "show mem[")
{
std::stringstream ss(command.substr(9));
uint32_t from;
uint32_t to;
ss>>from;
ss>>to;
std::istream::char_type delim;
ss.read(&delim,1);
if(from > to || delim != ']')
{
return "invalid format '" + command.substr(5) + "'";
}
uint32_t numWords=to-from+1;
uint32_t buffer[numWords];
if(!interface_->readMem(from,numWords,buffer))
{
return "fetch memory at addr " + std::to_string(from) + "failed";
}
std::stringstream ss2;
for(uint32_t i=0;i<numWords;++i)
{
ss2<<qfp32_t::initFromRaw(buffer[i])<<"\n";
}
return ss2.str().substr(0,ss2.str().length()-1);
}
if(command.substr(0,5) == "show ")
{
std::string subCommand=command.substr(5);
if(subCommand.substr(0,9) == "callstack")
{
return getCallStack();
}
else
{
return getSymbolInfo(subCommand);
}
}
else if(command.substr(0,4) == "show")
{
return getCodeInfo(150);
}
else if(command.substr(0,4) == "step" || command.substr(0,4) == "run ")
{
uint32_t codeAddr=interface_->getPC()+1;
if(command.substr(0,4) == "run ")
{
if(command.at(4) >= '0' && command.at(4) <= '9')
{
std::stringstream ss(command.substr(4));
ss >> codeAddr;
}
else
{
codeAddr=lineStringToAddr(command.substr(4));
}
if(codeAddr > codeSize_ || codeAddr == 0xFFFFFFFF)
{
return std::string("invalid string '") + command.substr(4) + "'";
}
}
callInfoValid_=false;
DebuggerInterface::_Run result=interface_->runToAddr(codeAddr);
switch(result.result_)
{
case DebuggerInterface::_Run::ACCESS_FAULT_READ:
return std::string("read fault at ") + std::to_string(result.addr_);
case DebuggerInterface::_Run::ACCESS_FAULT_WRITE:
return std::string("write fault at ") + std::to_string(result.addr_);
case DebuggerInterface::_Run::BREAKPOINT_HIT:
return std::string("hit break at ") + std::to_string(result.addr_);
case DebuggerInterface::_Run::OK:
return "ok";
default:
return "error";
}
}
else if(command.substr(0,5) == "reset")
{
interface_->reset();
return "ok";
}
else if(command.substr(0,5) == "badd ")
{
uint32_t codeAddr=lineStringToAddr(command.substr(5));
bool breakpointOk=interface_->addBreakpoint(codeAddr);
if(!breakpointOk)
{
return "failed to set breakpoint '" + command.substr(5) + "'";
}
return "ok";
}
else if(command.substr(0,4) == "brm ")
{
uint32_t codeAddr=lineStringToAddr(command.substr(4));
bool breakpointOk=interface_->removeBreakpoint(codeAddr);
if(!breakpointOk)
{
return "failed to remove breakpoint '" + command.substr(4) + "'";
}
return "ok";
}
else if(command.substr(0,4) == "quit")
{
return "";
}
return "invalid command";
}
uint32_t lineStringToAddr(const std::string &line)
{
uint32_t pos=line.find(":");
if(pos == std::string::npos)
{
return 0xFFFFFFFF;
}
std::string file=line.substr(0,pos);
uint32_t offsetInFile=0;
std::stringstream ss(line.substr(pos+1));
ss>>offsetInFile;
--offsetInFile; //make zero based offset
auto it=fileToLineMap_.find(file);
if(it == fileToLineMap_.end())
{
return 0xFFFFFFFF;
}
std::pair<uint32_t,uint32_t> lineInfo={0U,0U};//line,offset cause file can exist more than once
while(it != fileToLineMap_.end() && it->first == file)
{
std::cout<<"entry ["<<(it->first)<<"]:\n "<<(it->second.first)<<"\n "<<(it->second.second)<<"\n";
if(it->second.first > lineInfo.first && it->second.second <= offsetInFile)
{
lineInfo=it->second;
}
++it;
}
uint32_t totalLine=lineInfo.first-lineInfo.second+offsetInFile;
auto j=lineToAddrMap_.lower_bound(totalLine);
if(j == lineToAddrMap_.end())
{
return 0xFFFFFFFF;
}
return j->second;
}
std::string getFunctionFromAddr(uint32_t addr)
{
auto it=--(addrToFunctionMap_.upper_bound(addr));
CodeGen::_FunctionInfo func=functionMap_.find(it->second)->second;
if(func.address_ > addr || addr > (func.address_+func.size_))
{
return "";
}
return it->second;
}
uint32_t getLineFromAddr(uint32_t addr)
{
auto it=addrToLineMap_.lower_bound(addr);
if(it == addrToLineMap_.end())
{
return 0xFFFFFFFF;
}
return it->second;
}
std::string getSymbolInfo(const std::string &symbol)
{
//get IRS
auto callInfo=fetchCallInfo();
uint32_t irs=callInfo.back().irsAddr_;
//get context
std::string function=getFunctionFromAddr(interface_->getPC());
if(function.length() == 0)
{
return "no context found";
}
const CodeGen::_FunctionInfo &fi=functionMap_.find(function)->second;
uint32_t symRef=fi.symbols_->findSymbol(Stream::String(symbol.c_str(),0,symbol.length()));
SymbolMap::_Symbol sym;
if(symRef == SymbolMap::InvalidLink)
{
symRef=global_.findSymbol(Stream::String(symbol.c_str(),0,symbol.length()));
if(symRef == SymbolMap::InvalidLink)
{
return std::string("symbol '") + symbol + "' not found in context <" + function + ">";
}
sym=global_[symRef];
}
else
{
sym=(*(fi.symbols_))[symRef];
}
bool markMaybeInvalid=interface_->getPC() > sym.lastAccess_;
uint32_t numElements=1;
if(sym.flagIsArray_)
{
numElements=sym.allocatedSize_;
}
qfp32_t data[numElements];
if(sym.flagConst_ == 0)
{
bool readOk=interface_->readMem(irs+sym.allocatedAddr_,numElements,reinterpret_cast<uint32_t*>(data));
if(!readOk)
{
return std::string("reading '") + symbol + "' failed";
}
}
else
{
data[0]=sym.constValue_.toRealQfp32();
}
std::stringstream ss;
ss << symbol << " = ";
if(sym.flagIsArray_)
{
ss<<"[";
}
if(markMaybeInvalid)
{
ss<<"\x1B[31m";
}
for(uint32_t i=0;i<numElements;++i)
{
ss<<data[i];
if(i < (numElements-1))
{
ss<<" ";
}
}
ss<<"\x1B[0m";
if(sym.flagIsArray_)
{
ss<<"]";
}
return ss.str();
}
std::string getCodeInfo(int32_t numLinesShow)
{
int32_t line=interface_->getPC();//addrToLineMap_.lower_bound(interface_->getPC())->second;
int32_t from=std::max(line-numLinesShow,0);
int32_t to=std::min(line+numLinesShow,(int32_t)codeSize_);
std::vector<std::string> disasm=DisAsm::getLinesFromCode(code_+from,to-from+1);
uint32_t x=disasm.size();
std::string result;
uint32_t j=from;
auto i=addrToLineMap_.lower_bound(from);
while(j <= to)
{
std::string s;
if(addrToFunctionMap_.find(j) != addrToFunctionMap_.end())
{
result+="\x1B[36mfunction " + addrToFunctionMap_.find(j)->second + "\n\x1B[0m";
}
if(i != addrToLineMap_.end() && j == i->first)
{
uint32_t codeLine=i->second;
++i;
if(codeLine == 0)
{
s="\x1B[36mentry vector";
}
else if(disasm[j-from] != "nop")
{
auto file=--(lineToFileMap_.upper_bound(codeLine));
int32_t codeOffset=codeLine-file->first+file->second.second;
std::string name=file->second.first;
s+="\x1B[36m"+filesAsLineVector_.find(name)->second[codeOffset];
s.replace(s.rfind("\n"),1," ");
s+="(" + name + ":" + std::to_string(codeOffset+1) + ")";
}
}
std::string out=std::to_string(j)+". "+disasm[j-from];
if(j == line)
{
out="\x1B[31m"+out;
}
while(out.length() < 30) out.push_back(' ');
out+=s+"\x1B[0m";
result+=out;
if(j != to)
{
result+="\n";
}
++j;
}
return result;
}
std::string getCallStack()
{
auto callInfo=fetchCallInfo();
std::string result;
for(auto &i : callInfo)
{
std::string function=getFunctionFromAddr(i.addr_);
uint32_t line=getLineFromAddr(i.addr_)+1;//make one based
auto it=--lineToFileMap_.upper_bound(line);
std::string file=it->second.first;
line-=it->first-it->second.second;
result+=function + " (" + file + ":" + std::to_string(line) + ")\n";
}
return result.substr(0,result.size()-1);
}
struct _CallInfo
{
uint32_t addr_;
uint32_t irsAddr_;
};
std::vector<_CallInfo> extractCallInfo(const uint32_t *localMem,uint32_t size)
{
std::vector<_CallInfo> callInfo;
callInfo.push_back({0,0});
int32_t curIRS=0;
for(int32_t i=0;i<(size-4);++i)
{
if(localMem[i+2] == qfp32_t(curIRS).getAsRawUint())
{
int32_t jmpBackAddr=(int32_t)qfp32_t::initFromRaw(localMem[i+1]);
if(jmpBackAddr >= 5 && jmpBackAddr < codeSize_ && code_[jmpBackAddr-1] == SLCode::Goto::create())
{
//check addr
std::pair<qfp32_t,uint32_t> callAddr=getValueFromLoad(jmpBackAddr-2);
if(addrToFunctionMap_.find((int32_t)(callAddr.first)) == addrToFunctionMap_.end())
{
continue;
}
if(localMem[i+0] != qfp32_t(i).getAsRawUint())
{
continue;
}
std::pair<qfp32_t,uint32_t> retAddr=getValueFromLoad(jmpBackAddr-2-callAddr.second-5);
if(((int32_t)(retAddr.first)) != jmpBackAddr)
{
continue;
}
curIRS=(int32_t)qfp32_t::initFromRaw(localMem[i+0]);
(--callInfo.end())->addr_=jmpBackAddr;
callInfo.push_back({0,curIRS});
}
}
}
(--callInfo.end())->addr_=interface_->getPC();
return callInfo;
}
std::pair<qfp32_t,uint32_t> getValueFromLoad(uint32_t addr)
{
_Instr instr[3]={{0,0},{0,0},{0,0}};
int32_t i=0;
for(;i<3;++i)
{
_Instr cur={code_[addr-i],0};
if(!cur.isLoadAddr())
{
break;
}
instr[2]=instr[1];
instr[1]=instr[0];
instr[0]=cur;
}
return {_Instr::restoreValueFromLoad(instr[0],instr[1],instr[2]),i};
}
const std::vector<_CallInfo>& fetchCallInfo()
{
if(!callInfoValid_)
{
uint32_t buffer[512];
if(interface_->readMem(0,512,buffer))
{
callInfoCache_=std::move(extractCallInfo(buffer,512));
callInfoValid_=true;
}
}
return callInfoCache_;
}
protected:
DebuggerInterface *interface_;
SymbolMap global_;
std::map<std::string,CodeGen::_FunctionInfo> functionMap_;
std::map<uint32_t,std::pair<std::string,uint32_t> > lineToFileMap_;
std::map<uint32_t,std::string> addrToFunctionMap_;
std::map<uint32_t,uint32_t> addrToLineMap_;
std::map<uint32_t,uint32_t> lineToAddrMap_;
std::map<std::string,std::vector<std::string> > filesAsLineVector_;
std::multimap<std::string,std::pair<uint32_t,uint32_t> > fileToLineMap_;
const uint16_t *code_;
uint32_t codeSize_;
uint32_t codeAddr_;
bool callInfoValid_;
std::vector<_CallInfo> callInfoCache_;
};
| 25.05838 | 108 | 0.568991 | [
"vector"
] |
a2e067f8ce6003972520d26e0c68d7817383cc59 | 6,837 | c | C | cmds/usr/swear.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 69 | 2018-03-08T18:24:44.000Z | 2022-02-24T13:43:53.000Z | cmds/usr/swear.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 3 | 2019-04-24T12:21:19.000Z | 2021-03-28T23:34:58.000Z | cmds/usr/swear.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 33 | 2017-12-23T05:06:58.000Z | 2021-08-16T02:42:59.000Z | // swear.c
#include <ansi.h>
inherit F_CLEAN_UP;
void create() { seteuid(getuid()); }
int main(object me, string arg)
{
object ob;
object old;
string msg;
if (!stringp(arg) || arg != "cancel" && sscanf(arg, "with %s", arg) != 1)
return notify_fail("你要和谁一同结义?\n");
if (me->is_busy() || me->is_fighting())
return notify_fail("好好忙你手头的事情!\n");
ob = present(arg, environment(me));
if (objectp(old = me->query_temp("pending/swear")) &&
(ob || arg == "cancel"))
{
if (old != ob)
{
write("你打消了和" + old->name(1) + "结义的念头。\n");
if (environment(old) == environment(me))
tell_object(old, me->name(1) + "打消了和你结义的念头。\n");
}
else if (old->query_temp("pending/answer/" + me->query("id"), 1))
return notify_fail("你正在向人家提出请求呢,可是人家还没有答应你。\n");
me->delete_temp("pending/swear");
old->delete_temp("pending/answer/" + me->query("id"));
if (arg == "cancel")
return 1;
}
if (!ob)
return notify_fail("这里没有这个人。\n");
if (me->query_temp("pending/answer/" + ob->query("id")) &&
ob->query_temp("pending/swear") == me)
return notify_fail("别人正在向你提议结拜呢,你究竟答应还是不答应?\n");
if (!ob->is_character())
{
message_vision(CYN "$N" CYN "盯着$n" CYN "自言自语"
"道:“咱们…咱们结拜吧!求求你了!"
"”看来是疯了。\n" NOR,
me, ob);
return 1;
}
if (ob == me)
{
message_vision("$N目光呆滞,两眼发直,口中念念有词。\n", me);
return 1;
}
if (me->query("age") < 18)
{
write("小毛孩子捣什么乱?一边玩去!\n");
return 1;
}
if (ob->query("age") < 18)
{
write(ob->name() + "还是一个小毛孩子,你就省省吧,别逗人家了。\n");
return 1;
}
if (!ob->query("can_speak"))
{
message_vision("$N望着$n傻笑的不停,不知道中了什么邪。\n", me, ob);
return 1;
}
if (stringp(me->query("born_family") != "没有") && me->query("born_family") == ob->query("born_family"))
{
write("你和人家是同族弟子,结拜个什么?\n");
return 1;
}
if (me->is_brother(ob))
{
write("你已经和他结义了,似乎没有必要再来一次吧。\n");
return 1;
}
if (mapp(me->query("brothers")) && sizeof(me->query("brothers")) > 12)
{
write("你结义的兄弟也太多了,连你自己都快记不清楚了。\n");
return 1;
}
if (!living(ob))
{
write(ob->name() + "现在昏迷不醒,无法理会你的请求。\n");
return 1;
}
me->start_busy(1);
switch (random(6))
{
case 0:
msg = "$N对$n大声说道:「$R,你我一见如故,何不就此结义?」\n";
break;
case 1:
msg = "$N叹道:「天下虽大,知音难觅,$nn,你我有缘,今日何不结"
"拜?」\n";
break;
case 2:
msg = "$N望着$n,喜不自胜道:「今日得遇$R,实乃三生有幸,你我"
"结拜可好?」\n";
break;
case 3:
msg = "$N跨上一步,大声道:「千金易得,良友难觅,$nn!你我何不"
"就此结拜?」\n";
break;
case 4:
msg = "$N道:「$nn!在下有意和你结为异姓骨肉,你看可好?」\n";
break;
default:
msg = "$N拉着$n的手,郑重道:「今日良辰,你我在此相逢,当真难"
"得,不如结拜可好?」\n";
break;
}
msg = replace_string(msg, "$nn", ob->name(1));
msg = replace_string(msg, "$R", RANK_D->query_respect(ob));
message_vision(HIW + msg + NOR, me, ob);
if (!userp(ob))
{
write("但是" + ob->name() + "面露难色,看来是不感兴趣。\n");
return 1;
}
tell_object(ob, YEL + me->name(1) + "请求和你结拜,你答应(right)还是不答应(refuse)?\n" NOR);
ob->set_temp("pending/answer/" + me->query("id") + "/right",
bind((: call_other, __FILE__, "do_right", ob, me :), ob));
ob->set_temp("pending/answer/" + me->query("id") + "/refuse",
bind((: call_other, __FILE__, "do_refuse", ob, me :), ob));
me->set_temp("pending/swear", ob);
return 1;
}
int do_right(object me, object ob)
{
string msg;
if (!ob || environment(ob) != environment(me))
return notify_fail("可惜啊,人家已经不在这儿了。\n");
if (!living(ob))
return notify_fail("人家现在听不到你说的话,还是算了吧。\n");
if (ob->query_temp("pending/swear") != me)
return notify_fail("人家现在已经不打算和你结拜了。\n");
ob->delete_temp("pending/swear");
if (me->is_brother(ob))
{
write("你已经和他结义了,似乎没有必要再来一次吧。\n");
return 1;
}
if (mapp(me->query("brothers")) && sizeof(me->query("brothers")) > 12)
{
message_vision("$N为难的对$n道:“不是我不想...只是...”\n",
me, ob);
write("你结义的兄弟也太多了,连你自己都快记不清楚了。\n");
return 1;
}
message_vision(HIW "$N看着$n,连连点头道:「" +
RANK_D->query_self(me) + "正有此意!甚"
"好,甚好!」\n\n" HIC "只见$N与$n两人"
"齐齐跪下,撮土为香,一起磕头发誓。\n\n"
" 虽非骨肉\n 情同手足\n "
"不是同年同月同日生\n 但求同年同月"
"同日死\n\n" NOR,
me, ob);
// 记录数据
me->set("brothers/" + ob->query("id"), ob->name(1));
ob->set("brothers/" + me->query("id"), me->name(1));
me->save();
ob->save();
switch (random(3))
{
case 0:
msg = "听说" + me->name(1) + "已和" +
ob->name(1) + "结为异姓骨肉,共闯江湖。";
break;
case 1:
msg = "据说" + me->name(1) + "和" + ob->name(1) +
"一见如故,已经结为异姓骨肉。";
break;
default:
msg = "听说" + me->name(1) + "与" + ob->name(1) +
"义结金兰,携手行走江湖。";
break;
}
CHANNEL_D->do_channel(this_object(), "rumor", msg);
return 1;
}
int do_refuse(object me, object ob)
{
string msg;
if (!ob || environment(ob) != environment(me))
return notify_fail("可惜啊,人家已经不在这儿了。\n");
if (!living(ob))
return notify_fail("人家现在听不到你说的话,还是算了吧。\n");
if (ob->query_temp("pending/swear") != me)
return notify_fail("人家现在已经不打算和你结拜了。\n");
ob->delete_temp("pending/swear");
switch (random(6))
{
case 0:
msg = "$N嘿嘿干笑了几声,清了清嗓子,对$n道:"
"「在下怎敢高攀?」\n";
break;
case 1:
msg = "$N一皱眉,对$n道:「这……这似乎不太好"
"吧?还是改日再说吧!」\n";
break;
case 2:
msg = "$N面有难色,道:「$nn,你的美意我心领了"
",只是…只是……唉!不说也罢。」\n";
break;
case 3:
msg = "$N叹了一口气道:「$nn,我只是觉得今日时"
"辰有些不美,谈及此事不太好,不太好啊!」\n";
break;
case 4:
msg = "$N嗯了一声,忽然道:「你我辈分不合,这"
"个,这个我看还是算了吧。」\n";
break;
default:
msg = "$N不看$n,只是顾左右而言它,看来是不"
"打算和$n结拜。\n";
break;
}
msg = replace_string(msg, "$nn", ob->name(1));
message_vision(CYN + msg + NOR, me, ob);
tell_object(ob, "看来人家对你没什么兴趣。\n");
return 1;
}
int help(object me)
{
write( @HELP
指令格式: swear cancel | with <someone>
和某人结义。
see also:brothers
HELP );
return 1;
}
| 24.68231 | 106 | 0.474185 | [
"object"
] |
a2e282c36a43b6f8d123c0cc58e9eeed2ebd9d2f | 2,062 | h | C | CoMJacobian/Jacobian.h | RikiHayashi/ComJacobian | 67e9673dbe2959bbea4792b402f4259e9516d5f7 | [
"MIT"
] | null | null | null | CoMJacobian/Jacobian.h | RikiHayashi/ComJacobian | 67e9673dbe2959bbea4792b402f4259e9516d5f7 | [
"MIT"
] | null | null | null | CoMJacobian/Jacobian.h | RikiHayashi/ComJacobian | 67e9673dbe2959bbea4792b402f4259e9516d5f7 | [
"MIT"
] | null | null | null | /*
The BSD License (BSD)
Copyright (c) 2016 RDC lab and Chiba Institute of Technology.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _JACOBIAN_H_
#define _JACOBIAN_H_
#include <iostream>
#include <Eigen/Core>
#include "Link.h"
using namespace Eigen;
using namespace MotionControl;
Matrix<double,3,1> calcMC(Link *ulink, int rootlink);
double calcTotalMass(Link *ulink, int rootlink);
Matrix<double,3,1> calcCoM(Link *ulink);
MatrixXd calcJacobian(Link *ulink, std::vector<int> idx);
#endif
| 45.822222 | 171 | 0.658584 | [
"vector"
] |
a2e35dbc019d89d7f1e2f4295fab0c94997b03eb | 634 | h | C | 0703-Kth-Largest-Element-in-a-Stream/cpp_0703/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | 12 | 2020-03-18T14:36:23.000Z | 2021-12-19T02:24:33.000Z | 0703-Kth-Largest-Element-in-a-Stream/cpp_0703/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | 0703-Kth-Largest-Element-in-a-Stream/cpp_0703/Solution1.h | ooooo-youwillsee/leetcode | 07b273f133c8cf755ea40b3ae9df242ce044823c | [
"MIT"
] | null | null | null | //
// Created by ooooo on 2019/10/30.
//
#ifndef CPP_0703_SOLUTION1_H
#define CPP_0703_SOLUTION1_H
#include <iostream>
#include <queue>
using namespace std;
class KthLargest {
private:
priority_queue<int, vector<int>, greater<int>> q;
int k;
public:
KthLargest(int k, vector<int> &nums) {
this->k = k;
for (auto item : nums) {
add(item);
}
}
int add(int val) {
if (q.size() < k) {
q.push(val);
} else if (q.top() < val) {
q.pop();
q.push(val);
}
return q.top();
}
};
#endif //CPP_0703_SOLUTION1_H
| 15.85 | 53 | 0.523659 | [
"vector"
] |
a2f606f09edee0472d261371224f6c50fe47f509 | 4,963 | h | C | resman/src/main/resman.h | Jonander98/resman | fd76d8871cd0b5bd1329072008355f884280049a | [
"MIT"
] | null | null | null | resman/src/main/resman.h | Jonander98/resman | fd76d8871cd0b5bd1329072008355f884280049a | [
"MIT"
] | null | null | null | resman/src/main/resman.h | Jonander98/resman | fd76d8871cd0b5bd1329072008355f884280049a | [
"MIT"
] | null | null | null | /**
* @author Jon Ander Jimenez
* @contact jonander.jimenez@gmail.com
*/
#pragma once
#include "pch.h"
#include "resource.h"
#include "utils/message_log.h"
#include "work_group.h"
class Resman
{
public://Public types
struct Config
{
//Maximum number of threads allowed
u8 maxThreads{ 4 };
/*
* Minimum number of resources that have to be in the queue of a thread to create a new one
* always respecting the maximum
*/
u8 minResourcesToFork{ 3 };
};
private://Private types
template <typename resource_type>
using resource_container = std::unordered_map<AResource::IdType, ResourcePtr<resource_type>>;
public:
//Makes sure all the resources get unloaded
~Resman();
Resman(Config = Config());
Resman(const Resman &) = delete;
Resman & operator=(const Resman &) = delete;
public:
/*
* If the load for the resource has been requested, a valid pointer to the resource is given.
* But it might be not loaded yet.
* If the id is not found, a non valid resource_ptr is returned
*/
template <typename resource_type>
ResourcePtr<resource_type> Get(const str_t &);
/*
* Returns a vector with a pointer to all the resources of the given
* type that have been loaded
*/
template <typename resource_type>
std::vector<ResourcePtr<resource_type>> GetAllOfType();
/*
* Loads a resource of the given type from the given path
*/
template <typename resource_type>
void Load(const Filepath &);
/*
* Loads a resource of the given type from the given path asyncronously
*/
template <typename resource_type>
void LoadAsync(const Filepath &);
/*
* Unloads the specified resource
*/
template<typename resource_type>
void Unload(const str_t &);
/*
* Unloads all the resources of the specified type
*/
template<typename resource_type>
void UnloadAllOfType();
/*
* Unloads all the resources
*/
void UnloadAll();
public://log and config
/*
* Sets the config of the resource manager
*/
void SetConfig(Config c);
/*
* Sets the log used to inform the user of possible problems
*/
void SetLog(const MessageLog &);
/*
* Returns the log in its current status
*/
const MessageLog & GetLog()const;
/*
* Prints information about the current resource manager state to the log
*/
const MessageLog & GetResourceManagerStatus();
/*
* Saves the current status of the resource manager to a file.
* onlyEverUsed: if true, only resources that have been used at some point will be saved
*/
void SaveToFile(const Filepath &, bool onlyEverUsed = false)const;
/*
* Loads a resourcemanager status from file.
* The types that were not registered will get ignored
*/
void FromFile(const Filepath&);
/*
* Loads a resourcemanager status from file.
* The template parameters are the types that want to be loaded from the file. If a type is not provided
* and it is found on the file, it is ignored
*/
template<typename ...resource_types>
void FromFileRestrictedTypes(const Filepath&);
public:
//Registers a resource type
template <typename resource_type>
void RegisterResource();
//Registers a group of resource types
template <typename resource_type, typename resource_type2, typename ...args>
void RegisterResource();
//Checks if a resource is registered
template <typename resource_type>
bool IsRegistered();
private:
/*
* Returns a pointer to the corresponding resource container.
* It returns null if the resource was not previously registered
*/
template <typename resource_type>
resource_container<resource_type>* GetResourceContainer();
//Performs all the static checks for all the structural requirements a resource must meet
template <typename resource_type>
constexpr void CheckResourceType();
/*
* Used for resource loading from file. It loads the resource if the id
* matches with any of the types. Otherwise, nothing happens
*/
template <typename resource_type, typename resource_type2, typename ...args>
void LoadIfSameType(RTTI::Type id, const Filepath& fp);
template<typename resource_type>
void LoadIfSameType(RTTI::Type id, const Filepath& fp);
//Internal helper version
bool IsRegistered(RTTI::Type typeId);
/*
* Loads a resource of the given type from the given path.
* Must specify if it should be asyncronous or not
*/
template <typename resource_type>
void InternalLoad(const Filepath &, bool is_async);
//Helper to reuse file loading code
void ForEachResourceInFile(const Filepath& fp, std::function<void(const Filepath&, size_t)> action) const;
private:
//A map from type id to the corresponding resource container
std::unordered_map<RTTI::Type, void*> m_resources;
//The log for the messages
mutable MessageLog m_log;
//The work group that will load asyncronously
WorkScheduling::WorkGroup m_workGroup;
//The config of the resource manager(related with threads)
Config m_config;
};
#include "resman.inl"
| 31.213836 | 108 | 0.725771 | [
"vector"
] |
a2f663c1815ddc486fe70cc1fe0ce27c9a4055a3 | 1,659 | h | C | src/developer/debug/zxdb/symbols/symbol_factory.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/developer/debug/zxdb/symbols/symbol_factory.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/developer/debug/zxdb/symbols/symbol_factory.h | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_SYMBOL_FACTORY_H_
#define SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_SYMBOL_FACTORY_H_
#include <inttypes.h>
#include <memory>
#include "src/lib/fxl/memory/ref_counted.h"
namespace zxdb {
class Symbol;
// This class converts the information from a LazySymbol to a real Symbol.
//
// Having this class be reference counted also solves the problem of lifetimes. The module may get
// unloaded, and with it the symbol information. It's too error-prone to require Symbols not be
// cached since they will be very common.
//
// This class allows each LazySymbol to have one reference-counted pointer (relatively lightweight)
// to the factory. The factory can then have one (expensive) weak pointer to the underlying module
// symbols. When the module is unloaded, the factory may still be around but it will return empty
// types.
//
// Last, this class allows types to be mocked without requiring that the full and complex Symbol
// interface be virtual and duplicated.
class SymbolFactory : public fxl::RefCountedThreadSafe<SymbolFactory> {
public:
// This function should never return null. To indicate failure, return a new default-constructed
// Symbol object.
virtual fxl::RefPtr<Symbol> CreateSymbol(uint64_t factory_data) = 0;
protected:
FRIEND_REF_COUNTED_THREAD_SAFE(SymbolFactory);
SymbolFactory() = default;
virtual ~SymbolFactory() = default;
};
} // namespace zxdb
#endif // SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_SYMBOL_FACTORY_H_
| 35.297872 | 99 | 0.778782 | [
"object"
] |
a2f6e9c6154b45090c61c98200934a55b4dfbfe6 | 2,051 | h | C | images/Sketch.app/Contents/Frameworks/BCFoundation.framework/Versions/A/Headers/BCObjectSorting.h | annstella/Myportfolio | 2498da736c572d3020e97a723ea6cff9304cefe9 | [
"MIT"
] | null | null | null | images/Sketch.app/Contents/Frameworks/BCFoundation.framework/Versions/A/Headers/BCObjectSorting.h | annstella/Myportfolio | 2498da736c572d3020e97a723ea6cff9304cefe9 | [
"MIT"
] | null | null | null | images/Sketch.app/Contents/Frameworks/BCFoundation.framework/Versions/A/Headers/BCObjectSorting.h | annstella/Myportfolio | 2498da736c572d3020e97a723ea6cff9304cefe9 | [
"MIT"
] | null | null | null | // Created by Pieter Omvlee on 05/08/2014.
// Copyright (c) 2014 Bohemian Coding. All rights reserved.
extern NSString * const BCSortableKeyName;
extern NSString * const BCSortableKeyContents;
extern NSString * const BCSortableKeyChildren;
@protocol BCSortable <NSObject>
@property (nonatomic, readonly) NSString *name;
@end
/**
This is a class that helps you sort an unordered array of named objects (for instance symbols / shared objects).
The result of this sorting is an array of dictionaries, each dictionary having two entries; BCSortableKeyName
and either BCSortableKeyChildren or BCSortableKeyContents.
The value under BCSortableKeyName is the name of the sorted item.
If a value is stored under BCSortableKeyChildren this is another array of dictionaries with the same format.
Otherwise the value stored under BCSortableKeyContents is one of the sortable objects.
*/
@interface BCObjectSorting : NSObject
/**
Returns an array of dictionaries guartanteed to be sorted in alphabetical order, but with no nesting.
*/
+ (NSArray <NSDictionary *> *)sortObjectsAlphabetically:(NSArray <id<BCSortable>> *)sortableObjects;
/**
Returns an array of dictionaries guartanteed to be both alphabetical order and nested.
The hierarchy is decided upon by the name of the object, similar to how filenames work:
If we have two objects named "A/B" and "A/C" they should both appear as B and C in a group named A.
In the above example the first object would be a \c dictionary named "A" with as its contents an array
of two more \c dictionaries titled B and C containing those objects.
*/
+ (NSArray <NSDictionary *> *)sortObjectsWithNesting:(NSArray <id<BCSortable>> *)sortableObjects;
/**
Returns an array of dictionaries guartanteed to be both alphabetical order and nested.
Unlike \c sortObjectsWithNesting: this method compresses any groups which contain one item so instead of A > B > C > D
we'd get A/B/C > D.
*/
+ (NSArray <NSDictionary *> *)sortObjectsWithCompressedNesting:(NSArray <id<BCSortable>> *)sortableObjects;
@end
| 45.577778 | 119 | 0.776207 | [
"object"
] |
a2fbe04a4a69dededbeee40be2a14e3e8beb8156 | 10,374 | c | C | apps/usb_host_msd_bootloader/bootloader/firmware/src/config/sam_e70_xult/system/fs/src/sys_fs_fat_interface.c | Microchip-MPLAB-Harmony/bootloader_apps_usb | 9f47d92d302afd894727a347747ff88fdc8153f2 | [
"0BSD"
] | 2 | 2020-09-14T04:42:21.000Z | 2021-04-14T09:12:25.000Z | apps/sdcard_bootloader/bootloader/firmware/src/config/sam_l22_xpro/system/fs/src/sys_fs_fat_interface.c | Microchip-MPLAB-Harmony/bootloader_apps_sdcard | 99c51156fb6e996d2faf89bf0bd2dc26f5d9db6c | [
"0BSD"
] | 1 | 2021-07-05T05:18:39.000Z | 2021-07-05T05:18:39.000Z | apps/sdcard_bootloader/bootloader/firmware/src/config/sam_l22_xpro/system/fs/src/sys_fs_fat_interface.c | Microchip-MPLAB-Harmony/bootloader_apps_sdcard | 99c51156fb6e996d2faf89bf0bd2dc26f5d9db6c | [
"0BSD"
] | 2 | 2021-06-04T14:49:02.000Z | 2021-11-08T16:05:48.000Z | /*******************************************************************************
* Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
#include "system/fs/sys_fs_fat_interface.h"
#include "system/fs/sys_fs.h"
typedef struct
{
uint8_t inUse;
FATFS volObj;
} FATFS_VOLUME_OBJECT;
typedef struct
{
uint8_t inUse;
FIL fileObj;
} FATFS_FILE_OBJECT;
typedef struct
{
uint8_t inUse;
DIR dirObj;
} FATFS_DIR_OBJECT;
static FATFS_VOLUME_OBJECT CACHE_ALIGN FATFSVolume[SYS_FS_VOLUME_NUMBER];
static FATFS_FILE_OBJECT CACHE_ALIGN FATFSFileObject[SYS_FS_MAX_FILES];
static FATFS_DIR_OBJECT CACHE_ALIGN FATFSDirObject[SYS_FS_MAX_FILES];
static uint8_t startupflag = 0;
typedef UINT(*STREAM_FUNC)(const BYTE*,UINT);
int FATFS_mount ( uint8_t vol )
{
FATFS *fs = NULL;
FRESULT res = FR_INT_ERR;
TCHAR path[3];
BYTE opt = 1; /* 0:Do not mount (delayed mount), 1:Mount immediately */
uint8_t index = 0;
if(0 == startupflag)
{
startupflag = 1;
for(index = 0; index != SYS_FS_VOLUME_NUMBER ; index++ )
{
FATFSVolume[index].inUse = false;
}
for(index = 0; index != SYS_FS_MAX_FILES ; index++ )
{
FATFSFileObject[index].inUse = false;
FATFSDirObject[index].inUse = false;
}
}
/* Check if the drive number is valid */
if (vol >= SYS_FS_VOLUME_NUMBER)
{
return FR_INVALID_DRIVE;
}
/* If the volume specified is already in use, then return failure, as we cannot mount it again */
if(FATFSVolume[vol].inUse == true)
{
return FR_INVALID_DRIVE;
}
else
{
fs = &FATFSVolume[vol].volObj;
}
path[0] = '0' + vol;
path[1] = ':';
path[2] = '\0';
res = f_mount(fs, (const TCHAR *)&path, opt);
if ((res == FR_OK) || (res == FR_NO_FILESYSTEM))
{
FATFSVolume[vol].inUse = true;
}
return ((int)res);
}
int FATFS_unmount ( uint8_t vol )
{
FRESULT res = FR_INT_ERR;
TCHAR path[3];
BYTE opt = 0;
uint32_t hFATfs =0;
if (vol >= SYS_FS_VOLUME_NUMBER)
{
return FR_INVALID_DRIVE;
}
/* If the volume specified not in use, then return failure, as we cannot unmount mount a free volume */
if(FATFSVolume[vol].inUse == false)
{
return FR_INVALID_DRIVE;
}
path[0] = '0' + vol;
path[1] = ':';
path[2] = '\0';
res = f_mount(NULL, (const TCHAR *)&path, opt);
if (res == FR_OK)
{
// free the volume
FATFSVolume[vol].inUse = false;
for(hFATfs = 0; hFATfs < SYS_FS_MAX_FILES; hFATfs++)
{
if(FATFSFileObject[hFATfs].inUse)
{
if (FATFSFileObject[hFATfs].fileObj.obj.fs == NULL)
{
FATFSFileObject[hFATfs].inUse = false;
}
else if(VolToPart[vol].pd == FATFSFileObject[hFATfs].fileObj.obj.fs->pdrv)
{
FATFSFileObject[hFATfs].inUse = false;
}
}
if(FATFSDirObject[hFATfs].inUse)
{
if (FATFSDirObject[hFATfs].dirObj.obj.fs == NULL)
{
FATFSDirObject[hFATfs].inUse = false;
}
else if(VolToPart[vol].pd == FATFSDirObject[hFATfs].dirObj.obj.fs->pdrv)
{
FATFSDirObject[hFATfs].inUse = false;
}
}
}
}
return ((int)res);
}
int FATFS_open (
uintptr_t handle, /* Pointer to the blank file object */
const char * path, /* Pointer to the file name */
uint8_t mode /* Access mode and file open mode flags */
)
{
FRESULT res = FR_INT_ERR;
uint32_t index = 0;
FIL *fp = NULL;
/* Convert the SYS_FS file open attributes to FAT FS attributes */
switch(mode)
{
case SYS_FS_FILE_OPEN_READ:
mode = FA_READ;
break;
default:
return ((int)res);
break;
}
for (index = 0; index < SYS_FS_MAX_FILES; index++)
{
if(FATFSFileObject[index].inUse == false)
{
FATFSFileObject[index].inUse = true;
fp = &FATFSFileObject[index].fileObj;
*(uintptr_t *)handle = (uintptr_t)&FATFSFileObject[index];
break;
}
}
res = f_open(fp, (const TCHAR *)path, mode);
if (res != FR_OK)
{
FATFSFileObject[index].inUse = false;
}
return ((int)res);
}
int FATFS_read (
uintptr_t handle, /* Pointer to the file object */
void* buff, /* Pointer to data buffer */
uint32_t btr, /* Number of bytes to read */
uint32_t* br /* Pointer to number of bytes read */
)
{
FRESULT res = FR_INT_ERR;
FATFS_FILE_OBJECT *ptr = (FATFS_FILE_OBJECT *)handle;
FIL *fp = &ptr->fileObj;
res = f_read(fp, buff, (UINT)btr, (UINT *)br);
return ((int)res);
}
int FATFS_close (
uintptr_t handle /* Pointer to the file object to be closed */
)
{
FRESULT res;
FATFS_FILE_OBJECT *ptr = (FATFS_FILE_OBJECT *)handle;
FIL *fp = &ptr->fileObj;
if(ptr->inUse == false)
{
return FR_INVALID_OBJECT;
}
res = f_close(fp);
if (res == FR_OK)
{
ptr->inUse = false;
}
return ((int)res);
}
int FATFS_lseek (
uintptr_t handle, /* Pointer to the file object */
uint32_t ofs /* File pointer from top of file */
)
{
FRESULT res;
FATFS_FILE_OBJECT *ptr = (FATFS_FILE_OBJECT *)handle;
FIL *fp = &ptr->fileObj;
res = f_lseek(fp, (FSIZE_t)ofs);
return ((int)res);
}
int FATFS_stat (
const char* path, /* Pointer to the file path */
uintptr_t fileInfo /* Pointer to file information to return */
)
{
FRESULT res;
FILINFO *finfo = (FILINFO *)fileInfo;
res = f_stat((const TCHAR *)path, finfo);
SYS_FS_FSTAT *fileStat = (SYS_FS_FSTAT *)fileInfo;
if ((res == FR_OK) && (fileStat->lfname != NULL))
{
/* Use fileStat->fname instead */
fileStat->lfname[0] = '\0';
}
return ((int)res);
}
int FATFS_getlabel (
const char* path, /* Path name of the logical drive number */
char* label, /* Pointer to a buffer to return the volume label */
uint32_t* vsn /* Pointer to a variable to return the volume serial number */
)
{
FRESULT res;
res = f_getlabel((const TCHAR *)path, (TCHAR *)label, (DWORD *)vsn);
return ((int)res);
}
int FATFS_getcwd (
char* buff, /* Pointer to the directory path */
uint32_t len /* Size of path */
)
{
FRESULT res;
res = f_getcwd((TCHAR *)buff, (UINT)len);
return ((int)res);
}
char* FATFS_gets (
char* buff, /* Pointer to the string buffer to read */
int len, /* Size of string buffer (characters) */
uintptr_t handle/* Pointer to the file object */
)
{
FATFS_FILE_OBJECT *ptr = (FATFS_FILE_OBJECT *)handle;
FIL *fp = &ptr->fileObj;
return ((char *)f_gets((TCHAR *)buff, len, fp));
}
int FATFS_opendir (
uintptr_t handle, /* Pointer to directory object to create */
const char* path /* Pointer to the directory path */
)
{
FRESULT res;
uint32_t index = 0;
DIR *dp = NULL;
for(index = 0; index < SYS_FS_MAX_FILES; index++)
{
if(FATFSDirObject[index].inUse == false)
{
FATFSDirObject[index].inUse = true;
dp = &FATFSDirObject[index].dirObj;
*(uintptr_t *)handle = (uintptr_t)&FATFSDirObject[index];
break;
}
}
if(index >= SYS_FS_MAX_FILES)
{
return FR_INVALID_OBJECT;
}
res = f_opendir(dp, (const TCHAR *)path);
if (res != FR_OK)
{
FATFSDirObject[index].inUse = false;
}
return ((int)res);
}
int FATFS_readdir (
uintptr_t handle, /* Pointer to the open directory object */
uintptr_t fileInfo /* Pointer to file information to return */
)
{
FRESULT res;
FATFS_DIR_OBJECT *ptr = (FATFS_DIR_OBJECT *)handle;
DIR *dp = &ptr->dirObj;
FILINFO *finfo = (FILINFO *)fileInfo;
res = f_readdir(dp, finfo);
SYS_FS_FSTAT *fileStat = (SYS_FS_FSTAT *)fileInfo;
if ((res == FR_OK) && (fileStat->lfname != NULL))
{
/* Use fileStat->fname instead */
fileStat->lfname[0] = '\0';
}
return ((int)res);
}
int FATFS_closedir (
uintptr_t handle /* Pointer to the directory object to be closed */
)
{
FRESULT res;
FATFS_DIR_OBJECT *ptr = (FATFS_DIR_OBJECT *)handle;
DIR *dp = &ptr->dirObj;
if(ptr->inUse == false)
{
return FR_INVALID_OBJECT;
}
res = f_closedir(dp);
if (res == FR_OK)
{
ptr->inUse = false;
}
return ((int)res);
}
int FATFS_chdir (
const char* path /* Pointer to the directory path */
)
{
FRESULT res;
res = f_chdir((const TCHAR *)path);
return ((int)res);
}
int FATFS_chdrive (
uint8_t drv /* Drive number */
)
{
FRESULT res;
TCHAR path[3];
path[0] = '0' + drv;
path[1] = ':';
path[2] = '\0';
res = f_chdrive((const TCHAR *)&path);
return ((int)res);
}
| 24.466981 | 107 | 0.584153 | [
"object"
] |
a2fcd07b0afda5c6b3392d61d74ba4c4d47ba079 | 4,646 | h | C | components/bookmarks/browser/titled_url_index.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/bookmarks/browser/titled_url_index.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/bookmarks/browser/titled_url_index.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_BOOKMARKS_BROWSER_TITLED_URL_INDEX_H_
#define COMPONENTS_BOOKMARKS_BROWSER_TITLED_URL_INDEX_H_
#include <stddef.h>
#include <map>
#include <string>
#include <vector>
#include "base/containers/flat_set.h"
#include "base/macros.h"
#include "base/optional.h"
#include "base/strings/string16.h"
#include "components/bookmarks/browser/titled_url_node_sorter.h"
#include "components/query_parser/query_parser.h"
namespace bookmarks {
class TitledUrlNode;
struct TitledUrlMatch;
// TitledUrlIndex maintains an index of paired titles and URLs for quick lookup.
//
// TitledUrlIndex maintains the index (index_) as a map of sets. The map (type
// Index) maps from a lower case string to the set (type TitledUrlNodeSet) of
// TitledUrlNodes that contain that string in their title or URL.
class TitledUrlIndex {
public:
using TitledUrlNodeSet = base::flat_set<const TitledUrlNode*>;
// Constructs a TitledUrlIndex. |sorter| is used to construct a sorted list
// of matches when matches are returned from the index. If null, matches are
// returned unsorted.
explicit TitledUrlIndex(
std::unique_ptr<TitledUrlNodeSorter> sorter = nullptr);
~TitledUrlIndex();
void SetNodeSorter(std::unique_ptr<TitledUrlNodeSorter> sorter);
// Invoked when a title/URL pair has been added to the model.
void Add(const TitledUrlNode* node);
// Invoked when a title/URL pair has been removed from the model.
void Remove(const TitledUrlNode* node);
// Returns up to |max_count| of matches containing each term from the text
// |query| in either the title, URL, or, if |match_ancestor_titles| is true,
// the titles of ancestor nodes. |matching_algorithm| determines the algorithm
// used by QueryParser internally to parse |query|.
std::vector<TitledUrlMatch> GetResultsMatching(
const base::string16& query,
size_t max_count,
query_parser::MatchingAlgorithm matching_algorithm,
bool match_ancestor_titles);
// For testing only.
TitledUrlNodeSet RetrieveNodesMatchingAllTermsForTesting(
const std::vector<base::string16>& terms,
query_parser::MatchingAlgorithm matching_algorithm) const {
return RetrieveNodesMatchingAllTerms(terms, matching_algorithm);
}
// For testing only.
TitledUrlNodeSet RetrieveNodesMatchingAnyTermsForTesting(
const std::vector<base::string16>& terms,
query_parser::MatchingAlgorithm matching_algorithm) const {
return RetrieveNodesMatchingAnyTerms(terms, matching_algorithm);
}
private:
using TitledUrlNodes = std::vector<const TitledUrlNode*>;
using Index = std::map<base::string16, TitledUrlNodeSet>;
// Constructs |sorted_nodes| by copying the matches in |matches| and sorting
// them.
void SortMatches(const TitledUrlNodeSet& matches,
TitledUrlNodes* sorted_nodes) const;
// Finds |query_nodes| matches in |node| and returns a TitledUrlMatch
// containing |node| and the matches.
base::Optional<TitledUrlMatch> MatchTitledUrlNodeWithQuery(
const TitledUrlNode* node,
const query_parser::QueryNodeVector& query_nodes,
bool match_ancestor_titles);
// Return matches for the specified |terms|. This is an intersection of each
// term's matches.
TitledUrlNodeSet RetrieveNodesMatchingAllTerms(
const std::vector<base::string16>& terms,
query_parser::MatchingAlgorithm matching_algorithm) const;
TitledUrlNodeSet RetrieveNodesMatchingAnyTerms(
const std::vector<base::string16>& terms,
query_parser::MatchingAlgorithm matching_algorithm) const;
// Return matches for the specified |term|. May return duplicates.
TitledUrlNodes RetrieveNodesMatchingTerm(
const base::string16& term,
query_parser::MatchingAlgorithm matching_algorithm) const;
// Returns the set of query words from |query|.
static std::vector<base::string16> ExtractQueryWords(
const base::string16& query);
// Return the index terms for |node|.
static std::vector<base::string16> ExtractIndexTerms(
const TitledUrlNode* node);
// Adds |node| to |index_|.
void RegisterNode(const base::string16& term, const TitledUrlNode* node);
// Removes |node| from |index_|.
void UnregisterNode(const base::string16& term, const TitledUrlNode* node);
Index index_;
std::unique_ptr<TitledUrlNodeSorter> sorter_;
DISALLOW_COPY_AND_ASSIGN(TitledUrlIndex);
};
} // namespace bookmarks
#endif // COMPONENTS_BOOKMARKS_BROWSER_TITLED_URL_INDEX_H_
| 35.738462 | 80 | 0.756134 | [
"vector",
"model"
] |
a2fd9e393fded303f3d394469d9bbec169451a28 | 3,482 | h | C | Driver/Inc/ea_drv_gpio.h | EderAndrade/accel-with-discof3 | 909963fcfcefc197e4a7aca45485bae51a943c83 | [
"MIT"
] | null | null | null | Driver/Inc/ea_drv_gpio.h | EderAndrade/accel-with-discof3 | 909963fcfcefc197e4a7aca45485bae51a943c83 | [
"MIT"
] | null | null | null | Driver/Inc/ea_drv_gpio.h | EderAndrade/accel-with-discof3 | 909963fcfcefc197e4a7aca45485bae51a943c83 | [
"MIT"
] | 1 | 2021-09-05T14:13:48.000Z | 2021-09-05T14:13:48.000Z |
/**
******************************************************************************
* @Company: Eder Andrade Ltda.
* @file : ea_drv_gpio.h
* @author : Eder Andrade
* @version: V0.0
* @date : 12/03/2021
* @brief : Header of GPIO driver
*****************************************************************************
*/
#ifdef GPIO_ENABLED
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __EA_DRV_GPIO_H
#define __EA_DRV_GPIO_H
/* Includes ------------------------------------------------------------------*/
// STMicroelectronics
#include "stm32f3xx_hal.h"
/* Define --------------------------------------------------------------------*/
#define NUM_OF_IOS (uint8_t)8
/* DEFINING PORT AND PINS FOR THE DIGITAL I/Os USED --------------------------*/
/* OUTPUTS -------------------------------------------------------------------*/
/* LEDs of STM32F3-DISCO board ************************************************/
#define BLUE_LED_Pin GPIO_PIN_8
#define BLUE_LED_GPIO_Port GPIOE
#define RED_LED_Pin GPIO_PIN_9
#define RED_LED_GPIO_Port GPIOE
#define ORANGE_LED_Pin GPIO_PIN_10
#define ORANGE_LED_GPIO_Port GPIOE
#define GREEN_LED_Pin GPIO_PIN_11
#define GREEN_LED_GPIO_Port GPIOE
#define BLUE_LEDE12_Pin GPIO_PIN_12
#define BLUE_LEDE12_GPIO_Port GPIOE
#define RED_LEDE13_Pin GPIO_PIN_13
#define RED_LEDE13_GPIO_Port GPIOE
#define ORANGE_LEDE14_Pin GPIO_PIN_14
#define ORANGE_LEDE14_GPIO_Port GPIOE
#define GREEN_LEDE15_Pin GPIO_PIN_15
#define GREEN_LEDE15_GPIO_Port GPIOE
/*----------------------------------------------------------------------------*/
/* INPUTS --------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/* Typedef -------------------------------------------------------------------*/
// These values helps to understand the code
typedef enum
{
/* Output *****************************************************************/
eLedBlue1 = 0 ,
eLedRed1 ,
eLedOrange1 ,
eLedGreen1 ,
eLedBlue2 ,
eLedRed2 ,
eLedOrange2 ,
eLedGreen2 ,
/* Input ******************************************************************/
}e_gpio_t;
// This struct combines port and pin in one location
typedef struct
{
GPIO_TypeDef *port;
uint16_t pin;
}st_gpio_pin_t;
// Struct that retains all information about GPIOs of application
typedef struct
{
/* Flags ******************************************************************/
uint8_t FlagEnable; // State of peripheral
/* Variables **************************************************************/
GPIO_PinState State[NUM_OF_IOS]; // Vector of GPIOs values stored
/* Function Pointers ******************************************************/
int8_t (*Open) (void);
int8_t (*Close)(void);
int8_t (*Write)(e_gpio_t, GPIO_PinState);
int8_t (*Read) (e_gpio_t);
}st_gpio_t;
/* Public objects ------------------------------------------------------------*/
extern st_gpio_t GPIO;
#endif /* __EA_DRV_GPIO_H */
#endif /* GPIO_ENABLED */
/*****************************END OF FILE**************************************/ | 36.270833 | 82 | 0.410971 | [
"vector"
] |
0c09451468eb57ca154fb83d93ef7b2d35fd0f82 | 1,458 | h | C | nubscript/nu_expr_empty.h | eantcal/nubscript | 02f738770a14cb476ad39338b3aa4f6f9de01c32 | [
"MIT"
] | null | null | null | nubscript/nu_expr_empty.h | eantcal/nubscript | 02f738770a14cb476ad39338b3aa4f6f9de01c32 | [
"MIT"
] | null | null | null | nubscript/nu_expr_empty.h | eantcal/nubscript | 02f738770a14cb476ad39338b3aa4f6f9de01c32 | [
"MIT"
] | null | null | null | //
// This file is part of nuBScript Project
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//
/* -------------------------------------------------------------------------- */
#ifndef __NU_EXPR_EMPTY_H__
#define __NU_EXPR_EMPTY_H__
/* -------------------------------------------------------------------------- */
#include "nu_expr_any.h"
#include "nu_variant.h"
/* -------------------------------------------------------------------------- */
namespace nu {
/* -------------------------------------------------------------------------- */
class expr_empty_t : public expr_any_t {
public:
//! ctors
expr_empty_t() = default;
expr_empty_t(const expr_empty_t&) = default;
expr_empty_t& operator=(const expr_empty_t&) = default;
//! It does nothing for an empty object
virtual variant_t eval(rt_prog_ctx_t&) const override
{
return variant_t(0);
}
//! Returns true for an empty expression
virtual bool empty() const noexcept override { return true; }
std::string name() const noexcept override { return ""; }
func_args_t get_args() const noexcept override
{
func_args_t dummy;
return dummy;
}
};
/* -------------------------------------------------------------------------- */
}
#endif // __NU_EXPR_EMPTY_H__
| 24.711864 | 80 | 0.495885 | [
"object"
] |
0c0e7f64bef10dfa898467e5758c45f24ee30192 | 3,264 | h | C | cocos2d/external/chipmunk/include/chipmunk/cpPolyShape.h | IoriKobayashi/BluetoothChecker | fb0127d756a2794be89e5a98b031109cdabfc977 | [
"MIT"
] | 140 | 2016-03-13T03:01:25.000Z | 2022-02-06T09:47:04.000Z | cocos2d/external/chipmunk/include/chipmunk/cpPolyShape.h | IoriKobayashi/BluetoothChecker | fb0127d756a2794be89e5a98b031109cdabfc977 | [
"MIT"
] | 469 | 2016-05-15T07:01:56.000Z | 2020-05-29T23:58:59.000Z | cocos2d/external/chipmunk/include/chipmunk/cpPolyShape.h | IoriKobayashi/BluetoothChecker | fb0127d756a2794be89e5a98b031109cdabfc977 | [
"MIT"
] | 72 | 2016-03-13T10:17:54.000Z | 2020-02-24T05:40:02.000Z | /* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/// @defgroup cpPolyShape cpPolyShape
/// @{
/// Allocate a polygon shape.
CP_EXPORT cpPolyShape* cpPolyShapeAlloc(void);
/// Initialize a polygon shape with rounded corners.
/// A convex hull will be created from the vertexes.
CP_EXPORT cpPolyShape* cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int count, const cpVect *verts, cpTransform transform, cpFloat radius);
/// Initialize a polygon shape with rounded corners.
/// The vertexes must be convex with a counter-clockwise winding.
CP_EXPORT cpPolyShape* cpPolyShapeInitRaw(cpPolyShape *poly, cpBody *body, int count, const cpVect *verts, cpFloat radius);
/// Allocate and initialize a polygon shape with rounded corners.
/// A convex hull will be created from the vertexes.
CP_EXPORT cpShape* cpPolyShapeNew(cpBody *body, int count, const cpVect *verts, cpTransform transform, cpFloat radius);
/// Allocate and initialize a polygon shape with rounded corners.
/// The vertexes must be convex with a counter-clockwise winding.
CP_EXPORT cpShape* cpPolyShapeNewRaw(cpBody *body, int count, const cpVect *verts, cpFloat radius);
/// Initialize a box shaped polygon shape with rounded corners.
CP_EXPORT cpPolyShape* cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width, cpFloat height, cpFloat radius);
/// Initialize an offset box shaped polygon shape with rounded corners.
CP_EXPORT cpPolyShape* cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box, cpFloat radius);
/// Allocate and initialize a box shaped polygon shape.
CP_EXPORT cpShape* cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height, cpFloat radius);
/// Allocate and initialize an offset box shaped polygon shape.
CP_EXPORT cpShape* cpBoxShapeNew2(cpBody *body, cpBB box, cpFloat radius);
/// Get the number of verts in a polygon shape.
CP_EXPORT int cpPolyShapeGetCount(const cpShape *shape);
/// Get the @c ith vertex of a polygon shape.
CP_EXPORT cpVect cpPolyShapeGetVert(const cpShape *shape, int index);
/// Get the radius of a polygon shape.
CP_EXPORT cpFloat cpPolyShapeGetRadius(const cpShape *shape);
/// @}
| 57.263158 | 144 | 0.762868 | [
"shape",
"transform"
] |
0c11996d302e95af2b0df78f2ab28962d3ba1a8b | 3,589 | h | C | RecoParticleFlow/PFClusterProducer/interface/PFEcalRecHitCreatorMaxSample.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | null | null | null | RecoParticleFlow/PFClusterProducer/interface/PFEcalRecHitCreatorMaxSample.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 2 | 2019-08-08T14:11:10.000Z | 2019-08-26T13:25:41.000Z | RecoParticleFlow/PFClusterProducer/interface/PFEcalRecHitCreatorMaxSample.h | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | #ifndef RecoParticleFlow_PFClusterProducer_PFEcalRecHitCreatorMaxSample_h
#define RecoParticleFlow_PFClusterProducer_PFEcalRecHitCreatorMaxSample_h
#include "RecoParticleFlow/PFClusterProducer/interface/PFRecHitCreatorBase.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHit.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
#include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
#include "DataFormats/EcalDetId/interface/EEDetId.h"
#include "DataFormats/EcalDetId/interface/EBDetId.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
#include "Geometry/CaloGeometry/interface/TruncatedPyramid.h"
#include "Geometry/Records/interface/CaloGeometryRecord.h"
#include "Geometry/EcalAlgo/interface/EcalEndcapGeometry.h"
#include "Geometry/EcalAlgo/interface/EcalBarrelGeometry.h"
#include "Geometry/CaloTopology/interface/EcalEndcapTopology.h"
#include "Geometry/CaloTopology/interface/EcalBarrelTopology.h"
#include "Geometry/CaloTopology/interface/EcalPreshowerTopology.h"
#include "RecoCaloTools/Navigation/interface/CaloNavigator.h"
template <typename Geometry, PFLayer::Layer Layer, int Detector>
class PFEcalRecHitCreatorMaxSample final : public PFRecHitCreatorBase {
public:
PFEcalRecHitCreatorMaxSample(const edm::ParameterSet& iConfig, edm::ConsumesCollector& iC)
: PFRecHitCreatorBase(iConfig, iC) {
recHitToken_ = iC.consumes<EcalRecHitCollection>(iConfig.getParameter<edm::InputTag>("src"));
}
void importRecHits(std::unique_ptr<reco::PFRecHitCollection>& out,
std::unique_ptr<reco::PFRecHitCollection>& cleaned,
const edm::Event& iEvent,
const edm::EventSetup& iSetup) override {
beginEvent(iEvent, iSetup);
edm::Handle<EcalRecHitCollection> recHitHandle;
edm::ESHandle<CaloGeometry> geoHandle;
iSetup.get<CaloGeometryRecord>().get(geoHandle);
// get the ecal geometry
const CaloSubdetectorGeometry* gTmp = geoHandle->getSubdetectorGeometry(DetId::Ecal, Detector);
const Geometry* ecalGeo = dynamic_cast<const Geometry*>(gTmp);
iEvent.getByToken(recHitToken_, recHitHandle);
for (const auto& erh : *recHitHandle) {
const DetId& detid = erh.detid();
auto energy = erh.energy();
auto time = erh.time();
std::shared_ptr<const CaloCellGeometry> thisCell = ecalGeo->getGeometry(detid);
// find rechit geometry
if (!thisCell) {
edm::LogError("PFEcalRecHitCreatorMaxSample")
<< "warning detid " << detid.rawId() << " not found in geometry" << std::endl;
continue;
}
reco::PFRecHit rh(thisCell, detid.rawId(), Layer, energy);
bool rcleaned = false;
bool keep = true;
bool hi = true; // this is std version for which the PF ZS is always applied
//Apply Q tests
for (const auto& qtest : qualityTests_) {
if (!qtest->test(rh, erh, rcleaned, hi)) {
keep = false;
}
}
if (keep) {
rh.setTime(time);
rh.setDepth(1);
out->push_back(rh);
} else if (rcleaned)
cleaned->push_back(rh);
}
}
protected:
edm::EDGetTokenT<EcalRecHitCollection> recHitToken_;
};
typedef PFEcalRecHitCreatorMaxSample<EcalBarrelGeometry, PFLayer::ECAL_BARREL, EcalBarrel> PFEBRecHitCreatorMaxSample;
typedef PFEcalRecHitCreatorMaxSample<EcalEndcapGeometry, PFLayer::ECAL_ENDCAP, EcalEndcap> PFEERecHitCreatorMaxSample;
#endif
| 38.180851 | 118 | 0.73586 | [
"geometry"
] |
0c26a3481fd9ec6fb8fa53b26ed19228dba60372 | 42,477 | h | C | src/BulletSoftBody/btSoftBody.h | iank-nv/bullet3 | 3deb17985e48d58a1cfc5c105139697d475da130 | [
"Zlib"
] | 1 | 2019-07-15T01:14:15.000Z | 2019-07-15T01:14:15.000Z | src/BulletSoftBody/btSoftBody.h | iank-nv/bullet3 | 3deb17985e48d58a1cfc5c105139697d475da130 | [
"Zlib"
] | 76 | 2018-10-27T16:59:36.000Z | 2022-03-30T17:40:39.000Z | src/BulletSoftBody/btSoftBody.h | iank-nv/bullet3 | 3deb17985e48d58a1cfc5c105139697d475da130 | [
"Zlib"
] | 1 | 2019-07-29T02:02:08.000Z | 2019-07-29T02:02:08.000Z | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btSoftBody implementation by Nathanael Presson
#ifndef _BT_SOFT_BODY_H
#define _BT_SOFT_BODY_H
#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btIDebugDraw.h"
#include "LinearMath/btVector3.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "BulletCollision/CollisionShapes/btConcaveShape.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "btSparseSDF.h"
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraint.h"
//#ifdef BT_USE_DOUBLE_PRECISION
//#define btRigidBodyData btRigidBodyDoubleData
//#define btRigidBodyDataName "btRigidBodyDoubleData"
//#else
#define btSoftBodyData btSoftBodyFloatData
#define btSoftBodyDataName "btSoftBodyFloatData"
static const btScalar OVERLAP_REDUCTION_FACTOR = 0.1;
static unsigned long seed = 243703;
//#endif //BT_USE_DOUBLE_PRECISION
class btBroadphaseInterface;
class btDispatcher;
class btSoftBodySolver;
/* btSoftBodyWorldInfo */
struct btSoftBodyWorldInfo
{
btScalar air_density;
btScalar water_density;
btScalar water_offset;
btScalar m_maxDisplacement;
btVector3 water_normal;
btBroadphaseInterface* m_broadphase;
btDispatcher* m_dispatcher;
btVector3 m_gravity;
btSparseSdf<3> m_sparsesdf;
btSoftBodyWorldInfo()
: air_density((btScalar)1.2),
water_density(0),
water_offset(0),
m_maxDisplacement(1000.f), //avoid soft body from 'exploding' so use some upper threshold of maximum motion that a node can travel per frame
water_normal(0, 0, 0),
m_broadphase(0),
m_dispatcher(0),
m_gravity(0, -10, 0)
{
}
};
///The btSoftBody is an class to simulate cloth and volumetric soft bodies.
///There is two-way interaction between btSoftBody and btRigidBody/btCollisionObject.
class btSoftBody : public btCollisionObject
{
public:
btAlignedObjectArray<const class btCollisionObject*> m_collisionDisabledObjects;
// The solver object that handles this soft body
btSoftBodySolver* m_softBodySolver;
//
// Enumerations
//
///eAeroModel
struct eAeroModel
{
enum _
{
V_Point, ///Vertex normals are oriented toward velocity
V_TwoSided, ///Vertex normals are flipped to match velocity
V_TwoSidedLiftDrag, ///Vertex normals are flipped to match velocity and lift and drag forces are applied
V_OneSided, ///Vertex normals are taken as it is
F_TwoSided, ///Face normals are flipped to match velocity
F_TwoSidedLiftDrag, ///Face normals are flipped to match velocity and lift and drag forces are applied
F_OneSided, ///Face normals are taken as it is
END
};
};
///eVSolver : velocities solvers
struct eVSolver
{
enum _
{
Linear, ///Linear solver
END
};
};
///ePSolver : positions solvers
struct ePSolver
{
enum _
{
Linear, ///Linear solver
Anchors, ///Anchor solver
RContacts, ///Rigid contacts solver
SContacts, ///Soft contacts solver
END
};
};
///eSolverPresets
struct eSolverPresets
{
enum _
{
Positions,
Velocities,
Default = Positions,
END
};
};
///eFeature
struct eFeature
{
enum _
{
None,
Node,
Link,
Face,
Tetra,
END
};
};
typedef btAlignedObjectArray<eVSolver::_> tVSolverArray;
typedef btAlignedObjectArray<ePSolver::_> tPSolverArray;
//
// Flags
//
///fCollision
struct fCollision
{
enum _
{
RVSmask = 0x000f, ///Rigid versus soft mask
SDF_RS = 0x0001, ///SDF based rigid vs soft
CL_RS = 0x0002, ///Cluster vs convex rigid vs soft
SDF_RD = 0x0003, ///DF based rigid vs deformable
SDF_RDF = 0x0004, ///DF based rigid vs deformable faces
SVSmask = 0x00F0, ///Rigid versus soft mask
VF_SS = 0x0010, ///Vertex vs face soft vs soft handling
CL_SS = 0x0020, ///Cluster vs cluster soft vs soft handling
CL_SELF = 0x0040, ///Cluster soft body self collision
VF_DD = 0x0050, ///Vertex vs face soft vs soft handling
/* presets */
Default = SDF_RS,
END
};
};
///fMaterial
struct fMaterial
{
enum _
{
DebugDraw = 0x0001, /// Enable debug draw
/* presets */
Default = DebugDraw,
END
};
};
//
// API Types
//
/* sRayCast */
struct sRayCast
{
btSoftBody* body; /// soft body
eFeature::_ feature; /// feature type
int index; /// feature index
btScalar fraction; /// time of impact fraction (rayorg+(rayto-rayfrom)*fraction)
};
/* ImplicitFn */
struct ImplicitFn
{
virtual ~ImplicitFn() {}
virtual btScalar Eval(const btVector3& x) = 0;
};
//
// Internal types
//
typedef btAlignedObjectArray<btScalar> tScalarArray;
typedef btAlignedObjectArray<btVector3> tVector3Array;
/* sCti is Softbody contact info */
struct sCti
{
const btCollisionObject* m_colObj; /* Rigid body */
btVector3 m_normal; /* Outward normal */
btScalar m_offset; /* Offset from origin */
btVector3 m_bary; /* Barycentric weights for faces */
};
/* sMedium */
struct sMedium
{
btVector3 m_velocity; /* Velocity */
btScalar m_pressure; /* Pressure */
btScalar m_density; /* Density */
};
/* Base type */
struct Element
{
void* m_tag; // User data
Element() : m_tag(0) {}
};
/* Material */
struct Material : Element
{
btScalar m_kLST; // Linear stiffness coefficient [0,1]
btScalar m_kAST; // Area/Angular stiffness coefficient [0,1]
btScalar m_kVST; // Volume stiffness coefficient [0,1]
int m_flags; // Flags
};
/* Feature */
struct Feature : Element
{
Material* m_material; // Material
};
/* Node */
struct Node : Feature
{
btVector3 m_x; // Position
btVector3 m_q; // Previous step position/Test position
btVector3 m_v; // Velocity
btVector3 m_vsplit; // Temporary Velocity in addintion to velocity used in split impulse
btVector3 m_vn; // Previous step velocity
btVector3 m_f; // Force accumulator
btVector3 m_n; // Normal
btScalar m_im; // 1/mass
btScalar m_area; // Area
btDbvtNode* m_leaf; // Leaf data
bool m_constrained; // constrained node
int m_battach : 1; // Attached
int index;
};
/* Link */
ATTRIBUTE_ALIGNED16(struct)
Link : Feature
{
btVector3 m_c3; // gradient
Node* m_n[2]; // Node pointers
btScalar m_rl; // Rest length
int m_bbending : 1; // Bending link
btScalar m_c0; // (ima+imb)*kLST
btScalar m_c1; // rl^2
btScalar m_c2; // |gradient|^2/c0
BT_DECLARE_ALIGNED_ALLOCATOR();
};
/* Face */
struct Face : Feature
{
Node* m_n[3]; // Node pointers
btVector3 m_normal; // Normal
btScalar m_ra; // Rest area
btDbvtNode* m_leaf; // Leaf data
btVector4 m_pcontact; // barycentric weights of the persistent contact
btVector3 m_n0, m_n1, m_vn;
int m_index;
};
/* Tetra */
struct Tetra : Feature
{
Node* m_n[4]; // Node pointers
btScalar m_rv; // Rest volume
btDbvtNode* m_leaf; // Leaf data
btVector3 m_c0[4]; // gradients
btScalar m_c1; // (4*kVST)/(im0+im1+im2+im3)
btScalar m_c2; // m_c1/sum(|g0..3|^2)
btMatrix3x3 m_Dm_inverse; // rest Dm^-1
btMatrix3x3 m_F;
btScalar m_element_measure;
};
/* TetraScratch */
struct TetraScratch
{
btMatrix3x3 m_F; // deformation gradient F
btScalar m_trace; // trace of F^T * F
btScalar m_J; // det(F)
btMatrix3x3 m_cofF; // cofactor of F
};
/* RContact */
struct RContact
{
sCti m_cti; // Contact infos
Node* m_node; // Owner node
btMatrix3x3 m_c0; // Impulse matrix
btVector3 m_c1; // Relative anchor
btScalar m_c2; // ima*dt
btScalar m_c3; // Friction
btScalar m_c4; // Hardness
// jacobians and unit impulse responses for multibody
btMultiBodyJacobianData jacobianData_normal;
btMultiBodyJacobianData jacobianData_t1;
btMultiBodyJacobianData jacobianData_t2;
btVector3 t1;
btVector3 t2;
};
class DeformableRigidContact
{
public:
sCti m_cti; // Contact infos
btMatrix3x3 m_c0; // Impulse matrix
btVector3 m_c1; // Relative anchor
btScalar m_c2; // inverse mass of node/face
btScalar m_c3; // Friction
btScalar m_c4; // Hardness
// jacobians and unit impulse responses for multibody
btMultiBodyJacobianData jacobianData_normal;
btMultiBodyJacobianData jacobianData_t1;
btMultiBodyJacobianData jacobianData_t2;
btVector3 t1;
btVector3 t2;
};
class DeformableNodeRigidContact : public DeformableRigidContact
{
public:
Node* m_node; // Owner node
};
class DeformableNodeRigidAnchor : public DeformableNodeRigidContact
{
public:
btVector3 m_local; // Anchor position in body space
};
class DeformableFaceRigidContact : public DeformableRigidContact
{
public:
Face* m_face; // Owner face
btVector3 m_contactPoint; // Contact point
btVector3 m_bary; // Barycentric weights
btVector3 m_weights; // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
};
struct DeformableFaceNodeContact
{
Node* m_node; // Node
Face* m_face; // Face
btVector3 m_bary; // Barycentric weights
btVector3 m_weights; // v_contactPoint * m_weights[i] = m_face->m_node[i]->m_v;
btVector3 m_normal; // Normal
btScalar m_margin; // Margin
btScalar m_friction; // Friction
btScalar m_imf; // inverse mass of the face at contact point
btScalar m_c0; // scale of the impulse matrix;
};
/* SContact */
struct SContact
{
Node* m_node; // Node
Face* m_face; // Face
btVector3 m_weights; // Weigths
btVector3 m_normal; // Normal
btScalar m_margin; // Margin
btScalar m_friction; // Friction
btScalar m_cfm[2]; // Constraint force mixing
};
/* Anchor */
struct Anchor
{
Node* m_node; // Node pointer
btVector3 m_local; // Anchor position in body space
btRigidBody* m_body; // Body
btScalar m_influence;
btMatrix3x3 m_c0; // Impulse matrix
btVector3 m_c1; // Relative anchor
btScalar m_c2; // ima*dt
};
/* Note */
struct Note : Element
{
const char* m_text; // Text
btVector3 m_offset; // Offset
int m_rank; // Rank
Node* m_nodes[4]; // Nodes
btScalar m_coords[4]; // Coordinates
};
/* Pose */
struct Pose
{
bool m_bvolume; // Is valid
bool m_bframe; // Is frame
btScalar m_volume; // Rest volume
tVector3Array m_pos; // Reference positions
tScalarArray m_wgh; // Weights
btVector3 m_com; // COM
btMatrix3x3 m_rot; // Rotation
btMatrix3x3 m_scl; // Scale
btMatrix3x3 m_aqq; // Base scaling
};
/* Cluster */
struct Cluster
{
tScalarArray m_masses;
btAlignedObjectArray<Node*> m_nodes;
tVector3Array m_framerefs;
btTransform m_framexform;
btScalar m_idmass;
btScalar m_imass;
btMatrix3x3 m_locii;
btMatrix3x3 m_invwi;
btVector3 m_com;
btVector3 m_vimpulses[2];
btVector3 m_dimpulses[2];
int m_nvimpulses;
int m_ndimpulses;
btVector3 m_lv;
btVector3 m_av;
btDbvtNode* m_leaf;
btScalar m_ndamping; /* Node damping */
btScalar m_ldamping; /* Linear damping */
btScalar m_adamping; /* Angular damping */
btScalar m_matching;
btScalar m_maxSelfCollisionImpulse;
btScalar m_selfCollisionImpulseFactor;
bool m_containsAnchor;
bool m_collide;
int m_clusterIndex;
Cluster() : m_leaf(0), m_ndamping(0), m_ldamping(0), m_adamping(0), m_matching(0), m_maxSelfCollisionImpulse(100.f), m_selfCollisionImpulseFactor(0.01f), m_containsAnchor(false)
{
}
};
/* Impulse */
struct Impulse
{
btVector3 m_velocity;
btVector3 m_drift;
int m_asVelocity : 1;
int m_asDrift : 1;
Impulse() : m_velocity(0, 0, 0), m_drift(0, 0, 0), m_asVelocity(0), m_asDrift(0) {}
Impulse operator-() const
{
Impulse i = *this;
i.m_velocity = -i.m_velocity;
i.m_drift = -i.m_drift;
return (i);
}
Impulse operator*(btScalar x) const
{
Impulse i = *this;
i.m_velocity *= x;
i.m_drift *= x;
return (i);
}
};
/* Body */
struct Body
{
Cluster* m_soft;
btRigidBody* m_rigid;
const btCollisionObject* m_collisionObject;
Body() : m_soft(0), m_rigid(0), m_collisionObject(0) {}
Body(Cluster* p) : m_soft(p), m_rigid(0), m_collisionObject(0) {}
Body(const btCollisionObject* colObj) : m_soft(0), m_collisionObject(colObj)
{
m_rigid = (btRigidBody*)btRigidBody::upcast(m_collisionObject);
}
void activate() const
{
if (m_rigid)
m_rigid->activate();
if (m_collisionObject)
m_collisionObject->activate();
}
const btMatrix3x3& invWorldInertia() const
{
static const btMatrix3x3 iwi(0, 0, 0, 0, 0, 0, 0, 0, 0);
if (m_rigid) return (m_rigid->getInvInertiaTensorWorld());
if (m_soft) return (m_soft->m_invwi);
return (iwi);
}
btScalar invMass() const
{
if (m_rigid) return (m_rigid->getInvMass());
if (m_soft) return (m_soft->m_imass);
return (0);
}
const btTransform& xform() const
{
static const btTransform identity = btTransform::getIdentity();
if (m_collisionObject) return (m_collisionObject->getWorldTransform());
if (m_soft) return (m_soft->m_framexform);
return (identity);
}
btVector3 linearVelocity() const
{
if (m_rigid) return (m_rigid->getLinearVelocity());
if (m_soft) return (m_soft->m_lv);
return (btVector3(0, 0, 0));
}
btVector3 angularVelocity(const btVector3& rpos) const
{
if (m_rigid) return (btCross(m_rigid->getAngularVelocity(), rpos));
if (m_soft) return (btCross(m_soft->m_av, rpos));
return (btVector3(0, 0, 0));
}
btVector3 angularVelocity() const
{
if (m_rigid) return (m_rigid->getAngularVelocity());
if (m_soft) return (m_soft->m_av);
return (btVector3(0, 0, 0));
}
btVector3 velocity(const btVector3& rpos) const
{
return (linearVelocity() + angularVelocity(rpos));
}
void applyVImpulse(const btVector3& impulse, const btVector3& rpos) const
{
if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
if (m_soft) btSoftBody::clusterVImpulse(m_soft, rpos, impulse);
}
void applyDImpulse(const btVector3& impulse, const btVector3& rpos) const
{
if (m_rigid) m_rigid->applyImpulse(impulse, rpos);
if (m_soft) btSoftBody::clusterDImpulse(m_soft, rpos, impulse);
}
void applyImpulse(const Impulse& impulse, const btVector3& rpos) const
{
if (impulse.m_asVelocity)
{
// printf("impulse.m_velocity = %f,%f,%f\n",impulse.m_velocity.getX(),impulse.m_velocity.getY(),impulse.m_velocity.getZ());
applyVImpulse(impulse.m_velocity, rpos);
}
if (impulse.m_asDrift)
{
// printf("impulse.m_drift = %f,%f,%f\n",impulse.m_drift.getX(),impulse.m_drift.getY(),impulse.m_drift.getZ());
applyDImpulse(impulse.m_drift, rpos);
}
}
void applyVAImpulse(const btVector3& impulse) const
{
if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
if (m_soft) btSoftBody::clusterVAImpulse(m_soft, impulse);
}
void applyDAImpulse(const btVector3& impulse) const
{
if (m_rigid) m_rigid->applyTorqueImpulse(impulse);
if (m_soft) btSoftBody::clusterDAImpulse(m_soft, impulse);
}
void applyAImpulse(const Impulse& impulse) const
{
if (impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity);
if (impulse.m_asDrift) applyDAImpulse(impulse.m_drift);
}
void applyDCImpulse(const btVector3& impulse) const
{
if (m_rigid) m_rigid->applyCentralImpulse(impulse);
if (m_soft) btSoftBody::clusterDCImpulse(m_soft, impulse);
}
};
/* Joint */
struct Joint
{
struct eType
{
enum _
{
Linear = 0,
Angular,
Contact
};
};
struct Specs
{
Specs() : erp(1), cfm(1), split(1) {}
btScalar erp;
btScalar cfm;
btScalar split;
};
Body m_bodies[2];
btVector3 m_refs[2];
btScalar m_cfm;
btScalar m_erp;
btScalar m_split;
btVector3 m_drift;
btVector3 m_sdrift;
btMatrix3x3 m_massmatrix;
bool m_delete;
virtual ~Joint() {}
Joint() : m_delete(false) {}
virtual void Prepare(btScalar dt, int iterations);
virtual void Solve(btScalar dt, btScalar sor) = 0;
virtual void Terminate(btScalar dt) = 0;
virtual eType::_ Type() const = 0;
};
/* LJoint */
struct LJoint : Joint
{
struct Specs : Joint::Specs
{
btVector3 position;
};
btVector3 m_rpos[2];
void Prepare(btScalar dt, int iterations);
void Solve(btScalar dt, btScalar sor);
void Terminate(btScalar dt);
eType::_ Type() const { return (eType::Linear); }
};
/* AJoint */
struct AJoint : Joint
{
struct IControl
{
virtual ~IControl() {}
virtual void Prepare(AJoint*) {}
virtual btScalar Speed(AJoint*, btScalar current) { return (current); }
static IControl* Default()
{
static IControl def;
return (&def);
}
};
struct Specs : Joint::Specs
{
Specs() : icontrol(IControl::Default()) {}
btVector3 axis;
IControl* icontrol;
};
btVector3 m_axis[2];
IControl* m_icontrol;
void Prepare(btScalar dt, int iterations);
void Solve(btScalar dt, btScalar sor);
void Terminate(btScalar dt);
eType::_ Type() const { return (eType::Angular); }
};
/* CJoint */
struct CJoint : Joint
{
int m_life;
int m_maxlife;
btVector3 m_rpos[2];
btVector3 m_normal;
btScalar m_friction;
void Prepare(btScalar dt, int iterations);
void Solve(btScalar dt, btScalar sor);
void Terminate(btScalar dt);
eType::_ Type() const { return (eType::Contact); }
};
/* Config */
struct Config
{
eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point)
btScalar kVCF; // Velocities correction factor (Baumgarte)
btScalar kDP; // Damping coefficient [0,1]
btScalar kDG; // Drag coefficient [0,+inf]
btScalar kLF; // Lift coefficient [0,+inf]
btScalar kPR; // Pressure coefficient [-inf,+inf]
btScalar kVC; // Volume conversation coefficient [0,+inf]
btScalar kDF; // Dynamic friction coefficient [0,1]
btScalar kMT; // Pose matching coefficient [0,1]
btScalar kCHR; // Rigid contacts hardness [0,1]
btScalar kKHR; // Kinetic contacts hardness [0,1]
btScalar kSHR; // Soft contacts hardness [0,1]
btScalar kAHR; // Anchors hardness [0,1]
btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only)
btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only)
btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only)
btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only)
btScalar maxvolume; // Maximum volume ratio for pose
btScalar timescale; // Time scale
int viterations; // Velocities solver iterations
int piterations; // Positions solver iterations
int diterations; // Drift solver iterations
int citerations; // Cluster solver iterations
int collisions; // Collisions flags
tVSolverArray m_vsequence; // Velocity solvers sequence
tPSolverArray m_psequence; // Position solvers sequence
tPSolverArray m_dsequence; // Drift solvers sequence
btScalar drag; // deformable air drag
btScalar m_maxStress; // Maximum principle first Piola stress
};
/* SolverState */
struct SolverState
{
btScalar sdt; // dt*timescale
btScalar isdt; // 1/sdt
btScalar velmrg; // velocity margin
btScalar radmrg; // radial margin
btScalar updmrg; // Update margin
};
/// RayFromToCaster takes a ray from, ray to (instead of direction!)
struct RayFromToCaster : btDbvt::ICollide
{
btVector3 m_rayFrom;
btVector3 m_rayTo;
btVector3 m_rayNormalizedDirection;
btScalar m_mint;
Face* m_face;
int m_tests;
RayFromToCaster(const btVector3& rayFrom, const btVector3& rayTo, btScalar mxt);
void Process(const btDbvtNode* leaf);
static /*inline*/ btScalar rayFromToTriangle(const btVector3& rayFrom,
const btVector3& rayTo,
const btVector3& rayNormalizedDirection,
const btVector3& a,
const btVector3& b,
const btVector3& c,
btScalar maxt = SIMD_INFINITY);
};
//
// Typedefs
//
typedef void (*psolver_t)(btSoftBody*, btScalar, btScalar);
typedef void (*vsolver_t)(btSoftBody*, btScalar);
typedef btAlignedObjectArray<Cluster*> tClusterArray;
typedef btAlignedObjectArray<Note> tNoteArray;
typedef btAlignedObjectArray<Node> tNodeArray;
typedef btAlignedObjectArray<btDbvtNode*> tLeafArray;
typedef btAlignedObjectArray<Link> tLinkArray;
typedef btAlignedObjectArray<Face> tFaceArray;
typedef btAlignedObjectArray<Tetra> tTetraArray;
typedef btAlignedObjectArray<Anchor> tAnchorArray;
typedef btAlignedObjectArray<RContact> tRContactArray;
typedef btAlignedObjectArray<SContact> tSContactArray;
typedef btAlignedObjectArray<Material*> tMaterialArray;
typedef btAlignedObjectArray<Joint*> tJointArray;
typedef btAlignedObjectArray<btSoftBody*> tSoftBodyArray;
//
// Fields
//
Config m_cfg; // Configuration
SolverState m_sst; // Solver state
Pose m_pose; // Pose
void* m_tag; // User data
btSoftBodyWorldInfo* m_worldInfo; // World info
tNoteArray m_notes; // Notes
tNodeArray m_nodes; // Nodes
tNodeArray m_renderNodes; // Nodes
tLinkArray m_links; // Links
tFaceArray m_faces; // Faces
tFaceArray m_renderFaces; // Faces
tTetraArray m_tetras; // Tetras
btAlignedObjectArray<TetraScratch> m_tetraScratches;
btAlignedObjectArray<TetraScratch> m_tetraScratchesTn;
tAnchorArray m_anchors; // Anchors
btAlignedObjectArray<DeformableNodeRigidAnchor> m_deformableAnchors;
tRContactArray m_rcontacts; // Rigid contacts
btAlignedObjectArray<DeformableNodeRigidContact> m_nodeRigidContacts;
btAlignedObjectArray<DeformableFaceNodeContact> m_faceNodeContacts;
btAlignedObjectArray<DeformableFaceRigidContact> m_faceRigidContacts;
tSContactArray m_scontacts; // Soft contacts
tJointArray m_joints; // Joints
tMaterialArray m_materials; // Materials
btScalar m_timeacc; // Time accumulator
btVector3 m_bounds[2]; // Spatial bounds
bool m_bUpdateRtCst; // Update runtime constants
btDbvt m_ndbvt; // Nodes tree
btDbvt m_fdbvt; // Faces tree
btDbvntNode* m_fdbvnt; // Faces tree with normals
btDbvt m_cdbvt; // Clusters tree
tClusterArray m_clusters; // Clusters
btScalar m_dampingCoefficient; // Damping Coefficient
btScalar m_sleepingThreshold;
btScalar m_maxSpeedSquared;
bool m_useFaceContact;
btAlignedObjectArray<btVector3> m_quads; // quadrature points for collision detection
btScalar repulsionStiffness;
btAlignedObjectArray<btVector4> m_renderNodesInterpolationWeights;
btAlignedObjectArray<btAlignedObjectArray<const btSoftBody::Node*> > m_renderNodesParents;
bool m_useSelfCollision;
bool m_usePostCollisionDamping;
btAlignedObjectArray<bool> m_clusterConnectivity; //cluster connectivity, for self-collision
btTransform m_initialWorldTransform;
btVector3 m_windVelocity;
btScalar m_restLengthScale;
//
// Api
//
/* ctor */
btSoftBody(btSoftBodyWorldInfo* worldInfo, int node_count, const btVector3* x, const btScalar* m);
/* ctor */
btSoftBody(btSoftBodyWorldInfo* worldInfo);
void initDefaults();
/* dtor */
virtual ~btSoftBody();
/* Check for existing link */
btAlignedObjectArray<int> m_userIndexMapping;
btSoftBodyWorldInfo* getWorldInfo()
{
return m_worldInfo;
}
void setDampingCoefficient(btScalar damping_coeff)
{
m_dampingCoefficient = damping_coeff;
}
void setUseFaceContact(bool useFaceContact)
{
m_useFaceContact = false;
}
///@todo: avoid internal softbody shape hack and move collision code to collision library
virtual void setCollisionShape(btCollisionShape* collisionShape)
{
}
bool checkLink(int node0,
int node1) const;
bool checkLink(const Node* node0,
const Node* node1) const;
/* Check for existring face */
bool checkFace(int node0,
int node1,
int node2) const;
/* Append material */
Material* appendMaterial();
/* Append note */
void appendNote(const char* text,
const btVector3& o,
const btVector4& c = btVector4(1, 0, 0, 0),
Node* n0 = 0,
Node* n1 = 0,
Node* n2 = 0,
Node* n3 = 0);
void appendNote(const char* text,
const btVector3& o,
Node* feature);
void appendNote(const char* text,
const btVector3& o,
Link* feature);
void appendNote(const char* text,
const btVector3& o,
Face* feature);
/* Append node */
void appendNode(const btVector3& x, btScalar m);
/* Append link */
void appendLink(int model = -1, Material* mat = 0);
void appendLink(int node0,
int node1,
Material* mat = 0,
bool bcheckexist = false);
void appendLink(Node* node0,
Node* node1,
Material* mat = 0,
bool bcheckexist = false);
/* Append face */
void appendFace(int model = -1, Material* mat = 0);
void appendFace(int node0,
int node1,
int node2,
Material* mat = 0);
void appendTetra(int model, Material* mat);
//
void appendTetra(int node0,
int node1,
int node2,
int node3,
Material* mat = 0);
/* Append anchor */
void appendDeformableAnchor(int node, btRigidBody* body);
void appendDeformableAnchor(int node, btMultiBodyLinkCollider* link);
void appendAnchor(int node,
btRigidBody* body, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
void appendAnchor(int node, btRigidBody* body, const btVector3& localPivot, bool disableCollisionBetweenLinkedBodies = false, btScalar influence = 1);
/* Append linear joint */
void appendLinearJoint(const LJoint::Specs& specs, Cluster* body0, Body body1);
void appendLinearJoint(const LJoint::Specs& specs, Body body = Body());
void appendLinearJoint(const LJoint::Specs& specs, btSoftBody* body);
/* Append linear joint */
void appendAngularJoint(const AJoint::Specs& specs, Cluster* body0, Body body1);
void appendAngularJoint(const AJoint::Specs& specs, Body body = Body());
void appendAngularJoint(const AJoint::Specs& specs, btSoftBody* body);
/* Add force (or gravity) to the entire body */
void addForce(const btVector3& force);
/* Add force (or gravity) to a node of the body */
void addForce(const btVector3& force,
int node);
/* Add aero force to a node of the body */
void addAeroForceToNode(const btVector3& windVelocity, int nodeIndex);
/* Add aero force to a face of the body */
void addAeroForceToFace(const btVector3& windVelocity, int faceIndex);
/* Add velocity to the entire body */
void addVelocity(const btVector3& velocity);
/* Set velocity for the entire body */
void setVelocity(const btVector3& velocity);
/* Add velocity to a node of the body */
void addVelocity(const btVector3& velocity,
int node);
/* Set mass */
void setMass(int node,
btScalar mass);
/* Get mass */
btScalar getMass(int node) const;
/* Get total mass */
btScalar getTotalMass() const;
/* Set total mass (weighted by previous masses) */
void setTotalMass(btScalar mass,
bool fromfaces = false);
/* Set total density */
void setTotalDensity(btScalar density);
/* Set volume mass (using tetrahedrons) */
void setVolumeMass(btScalar mass);
/* Set volume density (using tetrahedrons) */
void setVolumeDensity(btScalar density);
/* Transform */
void transform(const btTransform& trs);
/* Translate */
void translate(const btVector3& trs);
/* Rotate */
void rotate(const btQuaternion& rot);
/* Scale */
void scale(const btVector3& scl);
/* Get link resting lengths scale */
btScalar getRestLengthScale();
/* Scale resting length of all springs */
void setRestLengthScale(btScalar restLength);
/* Set current state as pose */
void setPose(bool bvolume,
bool bframe);
/* Set current link lengths as resting lengths */
void resetLinkRestLengths();
/* Return the volume */
btScalar getVolume() const;
/* Cluster count */
btVector3 getCenterOfMass() const
{
btVector3 com(0, 0, 0);
for (int i = 0; i < m_nodes.size(); i++)
{
com += (m_nodes[i].m_x * this->getMass(i));
}
com /= this->getTotalMass();
return com;
}
int clusterCount() const;
/* Cluster center of mass */
static btVector3 clusterCom(const Cluster* cluster);
btVector3 clusterCom(int cluster) const;
/* Cluster velocity at rpos */
static btVector3 clusterVelocity(const Cluster* cluster, const btVector3& rpos);
/* Cluster impulse */
static void clusterVImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
static void clusterDImpulse(Cluster* cluster, const btVector3& rpos, const btVector3& impulse);
static void clusterImpulse(Cluster* cluster, const btVector3& rpos, const Impulse& impulse);
static void clusterVAImpulse(Cluster* cluster, const btVector3& impulse);
static void clusterDAImpulse(Cluster* cluster, const btVector3& impulse);
static void clusterAImpulse(Cluster* cluster, const Impulse& impulse);
static void clusterDCImpulse(Cluster* cluster, const btVector3& impulse);
/* Generate bending constraints based on distance in the adjency graph */
int generateBendingConstraints(int distance,
Material* mat = 0);
/* Randomize constraints to reduce solver bias */
void randomizeConstraints();
/* Release clusters */
void releaseCluster(int index);
void releaseClusters();
/* Generate clusters (K-mean) */
///generateClusters with k=0 will create a convex cluster for each tetrahedron or triangle
///otherwise an approximation will be used (better performance)
int generateClusters(int k, int maxiterations = 8192);
/* Refine */
void refine(ImplicitFn* ifn, btScalar accurary, bool cut);
/* CutLink */
bool cutLink(int node0, int node1, btScalar position);
bool cutLink(const Node* node0, const Node* node1, btScalar position);
///Ray casting using rayFrom and rayTo in worldspace, (not direction!)
bool rayTest(const btVector3& rayFrom,
const btVector3& rayTo,
sRayCast& results);
/* Solver presets */
void setSolver(eSolverPresets::_ preset);
/* predictMotion */
void predictMotion(btScalar dt);
/* solveConstraints */
void solveConstraints();
/* staticSolve */
void staticSolve(int iterations);
/* solveCommonConstraints */
static void solveCommonConstraints(btSoftBody** bodies, int count, int iterations);
/* solveClusters */
static void solveClusters(const btAlignedObjectArray<btSoftBody*>& bodies);
/* integrateMotion */
void integrateMotion();
/* defaultCollisionHandlers */
void defaultCollisionHandler(const btCollisionObjectWrapper* pcoWrap);
void defaultCollisionHandler(btSoftBody* psb);
void setSelfCollision(bool useSelfCollision);
bool useSelfCollision();
void updateDeactivation(btScalar timeStep);
void setZeroVelocity();
bool wantsSleeping();
//
// Functionality to deal with new accelerated solvers.
//
/**
* Set a wind velocity for interaction with the air.
*/
void setWindVelocity(const btVector3& velocity);
/**
* Return the wind velocity for interaction with the air.
*/
const btVector3& getWindVelocity();
//
// Set the solver that handles this soft body
// Should not be allowed to get out of sync with reality
// Currently called internally on addition to the world
void setSoftBodySolver(btSoftBodySolver* softBodySolver)
{
m_softBodySolver = softBodySolver;
}
//
// Return the solver that handles this soft body
//
btSoftBodySolver* getSoftBodySolver()
{
return m_softBodySolver;
}
//
// Return the solver that handles this soft body
//
btSoftBodySolver* getSoftBodySolver() const
{
return m_softBodySolver;
}
//
// Cast
//
static const btSoftBody* upcast(const btCollisionObject* colObj)
{
if (colObj->getInternalType() == CO_SOFT_BODY)
return (const btSoftBody*)colObj;
return 0;
}
static btSoftBody* upcast(btCollisionObject* colObj)
{
if (colObj->getInternalType() == CO_SOFT_BODY)
return (btSoftBody*)colObj;
return 0;
}
//
// ::btCollisionObject
//
virtual void getAabb(btVector3& aabbMin, btVector3& aabbMax) const
{
aabbMin = m_bounds[0];
aabbMax = m_bounds[1];
}
//
// Private
//
void pointersToIndices();
void indicesToPointers(const int* map = 0);
int rayTest(const btVector3& rayFrom, const btVector3& rayTo,
btScalar& mint, eFeature::_& feature, int& index, bool bcountonly) const;
void initializeFaceTree();
void rebuildNodeTree();
btVector3 evaluateCom() const;
bool checkDeformableContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
bool checkDeformableFaceContact(const btCollisionObjectWrapper* colObjWrap, Face& f, btVector3& contact_point, btVector3& bary, btScalar margin, btSoftBody::sCti& cti, bool predict = false) const;
bool checkContact(const btCollisionObjectWrapper* colObjWrap, const btVector3& x, btScalar margin, btSoftBody::sCti& cti) const;
void updateNormals();
void updateBounds();
void updatePose();
void updateConstants();
void updateLinkConstants();
void updateArea(bool averageArea = true);
void initializeClusters();
void updateClusters();
void cleanupClusters();
void prepareClusters(int iterations);
void solveClusters(btScalar sor);
void applyClusters(bool drift);
void dampClusters();
void setSpringStiffness(btScalar k);
void initializeDmInverse();
void updateDeformation();
void advanceDeformation();
void applyForces();
void setMaxStress(btScalar maxStress);
void interpolateRenderMesh();
void setCollisionQuadrature(int N);
static void PSolve_Anchors(btSoftBody* psb, btScalar kst, btScalar ti);
static void PSolve_RContacts(btSoftBody* psb, btScalar kst, btScalar ti);
static void PSolve_SContacts(btSoftBody* psb, btScalar, btScalar ti);
static void PSolve_Links(btSoftBody* psb, btScalar kst, btScalar ti);
static void VSolve_Links(btSoftBody* psb, btScalar kst);
static psolver_t getSolver(ePSolver::_ solver);
static vsolver_t getSolver(eVSolver::_ solver);
void geometricCollisionHandler(btSoftBody* psb);
#define SAFE_EPSILON SIMD_EPSILON*10.0
void updateNode(btDbvtNode* node, bool use_velocity, bool margin)
{
if (node->isleaf())
{
btSoftBody::Node* n = (btSoftBody::Node*)(node->data);
ATTRIBUTE_ALIGNED16(btDbvtVolume) vol;
btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON; // use user defined margin or margin for floating point precision
if (use_velocity)
{
btVector3 points[2] = {n->m_x, n->m_x + m_sst.sdt * n->m_v};
vol = btDbvtVolume::FromPoints(points, 2);
vol.Expand(btVector3(pad, pad, pad));
}
else
{
vol = btDbvtVolume::FromCR(n->m_x, pad);
}
node->volume = vol;
return;
}
else
{
updateNode(node->childs[0], use_velocity, margin);
updateNode(node->childs[1], use_velocity, margin);
ATTRIBUTE_ALIGNED16(btDbvtVolume) vol;
Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
node->volume = vol;
}
}
void updateNodeTree(bool use_velocity, bool margin)
{
if (m_ndbvt.m_root)
updateNode(m_ndbvt.m_root, use_velocity, margin);
}
template <class DBVTNODE> // btDbvtNode or btDbvntNode
void updateFace(DBVTNODE* node, bool use_velocity, bool margin)
{
if (node->isleaf())
{
btSoftBody::Face* f = (btSoftBody::Face*)(node->data);
btScalar pad = margin ? m_sst.radmrg : SAFE_EPSILON; // use user defined margin or margin for floating point precision
ATTRIBUTE_ALIGNED16(btDbvtVolume) vol;
if (use_velocity)
{
btVector3 points[6] = {f->m_n[0]->m_x, f->m_n[0]->m_x + m_sst.sdt * f->m_n[0]->m_v,
f->m_n[1]->m_x, f->m_n[1]->m_x + m_sst.sdt * f->m_n[1]->m_v,
f->m_n[2]->m_x, f->m_n[2]->m_x + m_sst.sdt * f->m_n[2]->m_v};
vol = btDbvtVolume::FromPoints(points, 6);
}
else
{
btVector3 points[3] = {f->m_n[0]->m_x,
f->m_n[1]->m_x,
f->m_n[2]->m_x};
vol = btDbvtVolume::FromPoints(points, 3);
}
vol.Expand(btVector3(pad, pad, pad));
node->volume = vol;
return;
}
else
{
updateFace(node->childs[0], use_velocity, margin);
updateFace(node->childs[1], use_velocity, margin);
ATTRIBUTE_ALIGNED16(btDbvtVolume) vol;
Merge(node->childs[0]->volume, node->childs[1]->volume, vol);
node->volume = vol;
}
}
void updateFaceTree(bool use_velocity, bool margin)
{
if (m_fdbvt.m_root)
updateFace(m_fdbvt.m_root, use_velocity, margin);
if (m_fdbvnt)
updateFace(m_fdbvnt, use_velocity, margin);
}
template <typename T>
static inline T BaryEval(const T& a,
const T& b,
const T& c,
const btVector3& coord)
{
return (a * coord.x() + b * coord.y() + c * coord.z());
}
void applyRepulsionForce(btScalar timeStep, bool applySpringForce)
{
btAlignedObjectArray<int> indices;
{
// randomize the order of repulsive force
indices.resize(m_faceNodeContacts.size());
for (int i = 0; i < m_faceNodeContacts.size(); ++i)
indices[i] = i;
// static unsigned long seed = 243703;
#define NEXTRAND (seed = (1664525L * seed + 1013904223L) & 0xffffffff)
int i, ni;
for (i = 0, ni = indices.size(); i < ni; ++i)
{
btSwap(indices[i], indices[NEXTRAND % ni]);
}
}
for (int k = 0; k < m_faceNodeContacts.size(); ++k)
{
int i = indices[k];
btSoftBody::DeformableFaceNodeContact& c = m_faceNodeContacts[i];
btSoftBody::Node* node = c.m_node;
btSoftBody::Face* face = c.m_face;
const btVector3& w = c.m_bary;
const btVector3& n = c.m_normal;
btVector3 l = node->m_x - BaryEval(face->m_n[0]->m_x, face->m_n[1]->m_x, face->m_n[2]->m_x, w);
btScalar d = c.m_margin - n.dot(l);
d = btMax(btScalar(0),d);
const btVector3& va = node->m_v;
btVector3 vb = BaryEval(face->m_n[0]->m_v, face->m_n[1]->m_v, face->m_n[2]->m_v, w);
btVector3 vr = va - vb;
const btScalar vn = btDot(vr, n); // dn < 0 <==> opposing
if (vn > OVERLAP_REDUCTION_FACTOR * d / timeStep)
continue;
btVector3 vt = vr - vn*n;
btScalar I = 0;
if (applySpringForce)
I = -btMin(repulsionStiffness * timeStep * d, btScalar(1)/node->m_im * (OVERLAP_REDUCTION_FACTOR * d / timeStep - vn));
if (vn < 0)
I += btScalar(0.5)/node->m_im * vn;
bool face_constrained = false, node_constrained = node->m_constrained;
for (int i = 0; i < 3; ++i)
face_constrained |= face->m_n[i]->m_constrained;
btScalar I_tilde = 2.0*I /(1.0+w.length2());
// double the impulse if node or face is constrained.
if (face_constrained || node_constrained)
I_tilde *= 2.0;
if (!face_constrained)
{
for (int j = 0; j < 3; ++j)
face->m_n[j]->m_v += w[j]*n*I_tilde*node->m_im;
}
if (!node_constrained)
{
node->m_v -= I_tilde*node->m_im*n;
}
// apply frictional impulse
btScalar vt_norm = vt.safeNorm();
if (vt_norm > SIMD_EPSILON)
{
btScalar delta_vn = -2 * I * node->m_im;
btScalar mu = c.m_friction;
btScalar vt_new = btMax(btScalar(1) - mu * delta_vn / (vt_norm + SIMD_EPSILON), btScalar(0))*vt_norm;
I = btScalar(0.5)/node->m_im * (vt_norm-vt_new);
vt.safeNormalize();
I_tilde = 2.0*I /(1.0+w.length2());
// double the impulse if node or face is constrained.
if (face_constrained || node_constrained)
I_tilde *= 2.0;
if (!face_constrained)
{
for (int j = 0; j < 3; ++j)
face->m_n[j]->m_v += w[j]*vt*I_tilde*node->m_im;
}
if (!node_constrained)
{
node->m_v -= I_tilde*node->m_im*vt;
}
}
}
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
};
#endif //_BT_SOFT_BODY_H
| 31.604911 | 243 | 0.669256 | [
"object",
"shape",
"model",
"transform"
] |
0c28b5ff8909c4d38a7d95179e2b078c1a4c299e | 716 | h | C | NimbleGraphics/NimbleGraphics/include/RayHit.h | keaton-freude/Nimble | 04370a5ea2394c1c9ecc18a3c8538b448138186a | [
"MIT"
] | null | null | null | NimbleGraphics/NimbleGraphics/include/RayHit.h | keaton-freude/Nimble | 04370a5ea2394c1c9ecc18a3c8538b448138186a | [
"MIT"
] | 1 | 2016-12-22T07:22:55.000Z | 2017-04-14T22:03:48.000Z | NimbleGraphics/NimbleGraphics/include/RayHit.h | keaton-freude/Nimble | 04370a5ea2394c1c9ecc18a3c8538b448138186a | [
"MIT"
] | null | null | null | #pragma once
#include "Typedefs.h"
class RayHit
{
public:
RayHit();
RayHit(Vector3 origin, Vector3 hitLocation, float distance, bool hit);
~RayHit();
static RayHit NoHit();
// true if the ray intersection test was successful, else false
// if false, then state of this object is not valid
bool hit;
// distance from origin of ray to intersection
float distance;
// Location in world space of the ray intersection
Vector3 hit_location;
// Location in world space of the origin of the ray
// NOTE: Maybe un-needed, might be nice to track it all together though
// and you could pass this RayHit to other modules that maybe didn't have
// the origin Vector when it was created
Vector3 origin;
}; | 23.866667 | 74 | 0.736034 | [
"object",
"vector"
] |
0c2d40c5deeefa78805098443577c09580f67936 | 47,126 | c | C | source/programs/Xserver/hw/dmx/input/dmxinputinit.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-09-08T21:13:25.000Z | 2021-09-08T21:13:25.000Z | source/programs/Xserver/hw/dmx/input/dmxinputinit.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | null | null | null | source/programs/Xserver/hw/dmx/input/dmxinputinit.c | binaryblob01/zfree86 | e80ea992d87501b8e3e2d7c07a414591c2e11c70 | [
"Xnet",
"X11"
] | 1 | 2021-01-22T00:19:47.000Z | 2021-01-22T00:19:47.000Z | /* $XFree86: xc/programs/Xserver/hw/dmx/input/dmxinputinit.c,v 1.5 2005/10/14 15:16:26 tsi Exp $ */
/*
* Copyright 2002-2003 Red Hat Inc., Durham, North Carolina.
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation on the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* Authors:
* Rickard E. (Rik) Faith <faith@redhat.com>
*
*/
/** \file
* This file provides generic input support. Functions here set up
* input and lead to the calling of low-level device drivers for
* input. */
#define DMX_WINDOW_DEBUG 0
#include "dmxinputinit.h"
#include "dmxextension.h" /* For dmxInputCount */
#include "dmxdummy.h"
#include "dmxbackend.h"
#include "dmxconsole.h"
#include "dmxcommon.h"
#include "dmxevents.h"
#include "dmxmotion.h"
#include "dmxeq.h"
#include "dmxprop.h"
#include "config/dmxconfig.h"
#include "dmxcursor.h"
#include "lnx-keyboard.h"
#include "lnx-ms.h"
#include "lnx-ps2.h"
#include "usb-keyboard.h"
#include "usb-mouse.h"
#include "usb-other.h"
#include "usb-common.h"
#include "dmxsigio.h"
#include "dmxarg.h"
#include "inputstr.h"
#include "input.h"
#include "mipointer.h"
#include "windowstr.h"
#ifdef XINPUT
#include <X11/extensions/XI.h>
#include <X11/extensions/XIproto.h>
#include "exevents.h"
#define EXTENSION_PROC_ARGS void *
#include "extinit.h"
#endif
/* From XI.h */
#ifndef Relative
#define Relative 0
#endif
#ifndef Absolute
#define Absolute 1
#endif
DMXLocalInputInfoPtr dmxLocalCorePointer, dmxLocalCoreKeyboard;
static DMXLocalInputInfoRec DMXDummyMou = {
"dummy-mou", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_LOCAL, 1,
NULL, NULL, NULL, NULL, NULL, dmxDummyMouGetInfo
};
static DMXLocalInputInfoRec DMXDummyKbd = {
"dummy-kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_LOCAL, 1,
NULL, NULL, NULL, NULL, NULL, dmxDummyKbdGetInfo
};
static DMXLocalInputInfoRec DMXBackendMou = {
"backend-mou", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_BACKEND, 2,
dmxBackendCreatePrivate, dmxBackendDestroyPrivate,
dmxBackendInit, NULL, dmxBackendLateReInit, dmxBackendMouGetInfo,
dmxCommonMouOn, dmxCommonMouOff, dmxBackendUpdatePosition,
NULL, NULL, NULL,
dmxBackendCollectEvents, dmxBackendProcessInput, dmxBackendFunctions, NULL,
dmxCommonMouCtrl
};
static DMXLocalInputInfoRec DMXBackendKbd = {
"backend-kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_BACKEND,
1, /* With backend-mou or console-mou */
dmxCommonCopyPrivate, NULL,
dmxBackendInit, NULL, NULL, dmxBackendKbdGetInfo,
dmxCommonKbdOn, dmxCommonKbdOff, NULL,
NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, dmxCommonKbdCtrl, dmxCommonKbdBell
};
static DMXLocalInputInfoRec DMXConsoleMou = {
"console-mou", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_CONSOLE, 2,
dmxConsoleCreatePrivate, dmxConsoleDestroyPrivate,
dmxConsoleInit, dmxConsoleReInit, NULL, dmxConsoleMouGetInfo,
dmxCommonMouOn, dmxCommonMouOff, dmxConsoleUpdatePosition,
NULL, NULL, NULL,
dmxConsoleCollectEvents, NULL, dmxConsoleFunctions, dmxConsoleUpdateInfo,
dmxCommonMouCtrl
};
static DMXLocalInputInfoRec DMXConsoleKbd = {
"console-kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_CONSOLE,
1, /* With backend-mou or console-mou */
dmxCommonCopyPrivate, NULL,
dmxConsoleInit, dmxConsoleReInit, NULL, dmxConsoleKbdGetInfo,
dmxCommonKbdOn, dmxCommonKbdOff, NULL,
NULL, NULL, NULL,
NULL, NULL, NULL, NULL,
NULL, dmxCommonKbdCtrl, dmxCommonKbdBell
};
static DMXLocalInputInfoRec DMXCommonOth = {
"common-oth", DMX_LOCAL_OTHER, DMX_LOCAL_TYPE_COMMON, 1,
dmxCommonCopyPrivate, NULL,
NULL, NULL, NULL, dmxCommonOthGetInfo,
dmxCommonOthOn, dmxCommonOthOff
};
static DMXLocalInputInfoRec DMXLocalDevices[] = {
/* Dummy drivers that can compile on any OS */
#ifdef __linux__
/* Linux-specific drivers */
{
"kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_LOCAL, 1,
kbdLinuxCreatePrivate, kbdLinuxDestroyPrivate,
kbdLinuxInit, NULL, NULL, kbdLinuxGetInfo,
kbdLinuxOn, kbdLinuxOff, NULL,
kbdLinuxVTPreSwitch, kbdLinuxVTPostSwitch, kbdLinuxVTSwitch,
kbdLinuxRead, NULL, NULL, NULL,
NULL, kbdLinuxCtrl, kbdLinuxBell
},
{
"ms", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_LOCAL, 1,
msLinuxCreatePrivate, msLinuxDestroyPrivate,
msLinuxInit, NULL, NULL, msLinuxGetInfo,
msLinuxOn, msLinuxOff, NULL,
msLinuxVTPreSwitch, msLinuxVTPostSwitch, NULL,
msLinuxRead
},
{
"ps2", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_LOCAL, 1,
ps2LinuxCreatePrivate, ps2LinuxDestroyPrivate,
ps2LinuxInit, NULL, NULL, ps2LinuxGetInfo,
ps2LinuxOn, ps2LinuxOff, NULL,
ps2LinuxVTPreSwitch, ps2LinuxVTPostSwitch, NULL,
ps2LinuxRead
},
#endif
#ifdef HAS_LINUX_INPUT
/* USB drivers, currently only for
Linux, but relatively easy to port to
other OSs */
{
"usb-kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_LOCAL, 1,
usbCreatePrivate, usbDestroyPrivate,
kbdUSBInit, NULL, NULL, kbdUSBGetInfo,
kbdUSBOn, usbOff, NULL,
NULL, NULL, NULL,
kbdUSBRead, NULL, NULL, NULL,
NULL, kbdUSBCtrl
},
{
"usb-mou", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_LOCAL, 1,
usbCreatePrivate, usbDestroyPrivate,
mouUSBInit, NULL, NULL, mouUSBGetInfo,
mouUSBOn, usbOff, NULL,
NULL, NULL, NULL,
mouUSBRead
},
{
"usb-oth", DMX_LOCAL_OTHER, DMX_LOCAL_TYPE_LOCAL, 1,
usbCreatePrivate, usbDestroyPrivate,
othUSBInit, NULL, NULL, othUSBGetInfo,
othUSBOn, usbOff, NULL,
NULL, NULL, NULL,
othUSBRead
},
#endif
{
"dummy-mou", DMX_LOCAL_MOUSE, DMX_LOCAL_TYPE_LOCAL, 1,
NULL, NULL, NULL, NULL, NULL, dmxDummyMouGetInfo
},
{
"dummy-kbd", DMX_LOCAL_KEYBOARD, DMX_LOCAL_TYPE_LOCAL, 1,
NULL, NULL, NULL, NULL, NULL, dmxDummyKbdGetInfo
},
{ NULL } /* Must be last */
};
static void _dmxChangePointerControl(DMXLocalInputInfoPtr dmxLocal,
PtrCtrl *ctrl)
{
if (!dmxLocal) return;
dmxLocal->mctrl = *ctrl;
if (dmxLocal->mCtrl) dmxLocal->mCtrl(&dmxLocal->pDevice->public, ctrl);
}
/** Change the pointer control information for the \a pDevice. If the
* device sends core events, then also change the control information
* for all of the pointer devices that send core events. */
void dmxChangePointerControl(DeviceIntPtr pDevice, PtrCtrl *ctrl)
{
GETDMXLOCALFROMPDEVICE;
int i, j;
if (dmxLocal->sendsCore) { /* Do for all core devices */
for (i = 0; i < dmxNumInputs; i++) {
DMXInputInfo *dmxInput = &dmxInputs[i];
if (dmxInput->detached) continue;
for (j = 0; j < dmxInput->numDevs; j++)
if (dmxInput->devs[j]->sendsCore)
_dmxChangePointerControl(dmxInput->devs[j], ctrl);
}
} else { /* Do for this device only */
_dmxChangePointerControl(dmxLocal, ctrl);
}
}
static void _dmxKeyboardKbdCtrlProc(DMXLocalInputInfoPtr dmxLocal,
KeybdCtrl *ctrl)
{
dmxLocal->kctrl = *ctrl;
if (dmxLocal->kCtrl) {
dmxLocal->kCtrl(&dmxLocal->pDevice->public, ctrl);
#ifdef XKB
if (!noXkbExtension && dmxLocal->pDevice->kbdfeed) {
XkbEventCauseRec cause;
XkbSetCauseUnknown(&cause);
/* Generate XKB events, as necessary */
XkbUpdateIndicators(dmxLocal->pDevice, XkbAllIndicatorsMask, False,
NULL, &cause);
}
#endif
}
}
/** Change the keyboard control information for the \a pDevice. If the
* device sends core events, then also change the control information
* for all of the keyboard devices that send core events. */
void dmxKeyboardKbdCtrlProc(DeviceIntPtr pDevice, KeybdCtrl *ctrl)
{
GETDMXLOCALFROMPDEVICE;
int i, j;
if (dmxLocal->sendsCore) { /* Do for all core devices */
for (i = 0; i < dmxNumInputs; i++) {
DMXInputInfo *dmxInput = &dmxInputs[i];
if (dmxInput->detached) continue;
for (j = 0; j < dmxInput->numDevs; j++)
if (dmxInput->devs[j]->sendsCore)
_dmxKeyboardKbdCtrlProc(dmxInput->devs[j], ctrl);
}
} else { /* Do for this device only */
_dmxKeyboardKbdCtrlProc(dmxLocal, ctrl);
}
}
static void _dmxKeyboardBellProc(DMXLocalInputInfoPtr dmxLocal, int percent)
{
if (dmxLocal->kBell) dmxLocal->kBell(&dmxLocal->pDevice->public,
percent,
dmxLocal->kctrl.bell,
dmxLocal->kctrl.bell_pitch,
dmxLocal->kctrl.bell_duration);
}
/** Sound the bell on the device. If the device send core events, then
* sound the bell on all of the devices that send core events. */
void dmxKeyboardBellProc(int percent, DeviceIntPtr pDevice,
pointer ctrl, int unknown)
{
GETDMXLOCALFROMPDEVICE;
int i, j;
if (dmxLocal->sendsCore) { /* Do for all core devices */
for (i = 0; i < dmxNumInputs; i++) {
DMXInputInfo *dmxInput = &dmxInputs[i];
if (dmxInput->detached) continue;
for (j = 0; j < dmxInput->numDevs; j++)
if (dmxInput->devs[j]->sendsCore)
_dmxKeyboardBellProc(dmxInput->devs[j], percent);
}
} else { /* Do for this device only */
_dmxKeyboardBellProc(dmxLocal, percent);
}
}
#ifdef XKB
static void dmxKeyboardFreeNames(XkbComponentNamesPtr names)
{
if (names->keymap) XFree(names->keymap);
if (names->keycodes) XFree(names->keycodes);
if (names->types) XFree(names->types);
if (names->compat) XFree(names->compat);
if (names->symbols) XFree(names->symbols);
if (names->geometry) XFree(names->geometry);
}
#endif
static int dmxKeyboardOn(DeviceIntPtr pDevice, DMXLocalInitInfo *info)
{
#ifdef XKB
GETDMXINPUTFROMPDEVICE;
#else
DevicePtr pDev = &pDevice->public;
#endif
#ifdef XKB
if (noXkbExtension) {
#endif
if (!InitKeyboardDeviceStruct(pDev, &info->keySyms, info->modMap,
dmxKeyboardBellProc,
dmxKeyboardKbdCtrlProc))
return BadImplementation;
#ifdef XKB
} else {
XkbSetRulesDflts(dmxConfigGetXkbRules(),
dmxConfigGetXkbModel(),
dmxConfigGetXkbLayout(),
dmxConfigGetXkbVariant(),
dmxConfigGetXkbOptions());
if (XkbInitialMap) { /* Set with -xkbmap */
dmxLogInput(dmxInput,
"XKEYBOARD: From command line: %s\n", XkbInitialMap);
if ((info->names.keymap = strchr(XkbInitialMap, '/')))
++info->names.keymap;
else
info->names.keymap = XkbInitialMap;
info->names.keycodes = NULL;
info->names.types = NULL;
info->names.compat = NULL;
info->names.symbols = NULL;
info->names.geometry = NULL;
} else {
if (!info->force && (dmxInput->keycodes
|| dmxInput->symbols
|| dmxInput->geometry)) {
if (info->freenames) dmxKeyboardFreeNames(&info->names);
info->freenames = 0;
info->names.keycodes = dmxInput->keycodes;
info->names.types = NULL;
info->names.compat = NULL;
info->names.symbols = dmxInput->symbols;
info->names.geometry = dmxInput->geometry;
dmxLogInput(dmxInput, "XKEYBOARD: From command line: %s",
info->names.keycodes);
if (info->names.symbols && *info->names.symbols)
dmxLogInputCont(dmxInput, " %s", info->names.symbols);
if (info->names.geometry && *info->names.geometry)
dmxLogInputCont(dmxInput, " %s", info->names.geometry);
dmxLogInputCont(dmxInput, "\n");
} else if (info->names.keycodes) {
dmxLogInput(dmxInput, "XKEYBOARD: From device: %s",
info->names.keycodes);
if (info->names.symbols && *info->names.symbols)
dmxLogInputCont(dmxInput, " %s", info->names.symbols);
if (info->names.geometry && *info->names.geometry)
dmxLogInputCont(dmxInput, " %s", info->names.geometry);
dmxLogInputCont(dmxInput, "\n");
} else {
dmxLogInput(dmxInput, "XKEYBOARD: Defaults: %s %s %s %s %s\n",
dmxConfigGetXkbRules(),
dmxConfigGetXkbLayout(),
dmxConfigGetXkbModel(),
dmxConfigGetXkbVariant()
? dmxConfigGetXkbVariant() : "",
dmxConfigGetXkbOptions()
? dmxConfigGetXkbOptions() : "");
}
}
XkbInitKeyboardDeviceStruct(pDevice,
&info->names,
&info->keySyms,
info->modMap,
dmxKeyboardBellProc,
dmxKeyboardKbdCtrlProc);
}
if (info->freenames) dmxKeyboardFreeNames(&info->names);
#endif
return Success;
}
static int dmxDeviceOnOff(DeviceIntPtr pDevice, int what)
{
GETDMXINPUTFROMPDEVICE;
int fd;
DMXLocalInitInfo info;
#ifdef XINPUT
int i;
#endif
if (!dmxLocal) return BadImplementation;
if (dmxInput->detached) return Success;
memset(&info, 0, sizeof(info));
switch (what) {
case DEVICE_INIT:
if (dmxLocal->init) dmxLocal->init(pDev);
if (dmxLocal->get_info) dmxLocal->get_info(pDev, &info);
if (info.keyboard) { /* XKEYBOARD makes this a special case */
dmxKeyboardOn(pDevice, &info);
break;
}
if (info.keyClass) {
InitKeyClassDeviceStruct(pDevice, &info.keySyms, info.modMap);
}
if (info.buttonClass) {
InitButtonClassDeviceStruct(pDevice, info.numButtons, info.map);
}
if (info.valuatorClass) {
if (info.numRelAxes && dmxLocal->sendsCore) {
InitValuatorClassDeviceStruct(pDevice, info.numRelAxes,
miPointerGetMotionEvents,
miPointerGetMotionBufferSize(),
Relative);
#ifdef XINPUT
for (i = 0; i < info.numRelAxes; i++)
InitValuatorAxisStruct(pDevice, i, info.minval[0],
info.maxval[0], info.res[0],
info.minres[0], info.maxres[0]);
#endif
} else if (info.numRelAxes) {
InitValuatorClassDeviceStruct(pDevice, info.numRelAxes,
dmxPointerGetMotionEvents,
dmxPointerGetMotionBufferSize(),
Relative);
#ifdef XINPUT
for (i = 0; i < info.numRelAxes; i++)
InitValuatorAxisStruct(pDevice, i, info.minval[0],
info.maxval[0], info.res[0],
info.minres[0], info.maxres[0]);
#endif
} else if (info.numAbsAxes) {
InitValuatorClassDeviceStruct(pDevice, info.numAbsAxes,
dmxPointerGetMotionEvents,
dmxPointerGetMotionBufferSize(),
Absolute);
#ifdef XINPUT
for (i = 0; i < info.numAbsAxes; i++)
InitValuatorAxisStruct(pDevice, i+info.numRelAxes,
info.minval[i+1], info.maxval[i+1],
info.res[i+1], info.minres[i+1],
info.maxres[i+1]);
#endif
}
}
if (info.focusClass) InitFocusClassDeviceStruct(pDevice);
#ifdef XINPUT
if (info.proximityClass) InitProximityClassDeviceStruct(pDevice);
#endif
if (info.ptrFeedbackClass)
InitPtrFeedbackClassDeviceStruct(pDevice, dmxChangePointerControl);
if (info.kbdFeedbackClass)
InitKbdFeedbackClassDeviceStruct(pDevice, dmxKeyboardBellProc,
dmxKeyboardKbdCtrlProc);
if (info.intFeedbackClass || info.strFeedbackClass)
dmxLog(dmxWarning,
"Integer and string feedback not supported for %s\n",
pDevice->name);
if (!info.keyboard && (info.ledFeedbackClass || info.belFeedbackClass))
dmxLog(dmxWarning,
"Led and bel feedback not supported for non-keyboard %s\n",
pDevice->name);
break;
case DEVICE_ON:
if (!pDev->on) {
if (dmxLocal->on && (fd = dmxLocal->on(pDev)) >= 0)
dmxSigioRegister(dmxInput, fd);
pDev->on = TRUE;
}
break;
case DEVICE_OFF:
case DEVICE_CLOSE:
/* This can get called twice consecutively: once for a
* detached screen (DEVICE_OFF), and then again at server
* generation time (DEVICE_CLOSE). */
if (pDev->on) {
dmxSigioUnregister(dmxInput);
if (dmxLocal->off) dmxLocal->off(pDev);
pDev->on = FALSE;
}
break;
}
if (info.keySyms.map && info.freemap) {
XFree(info.keySyms.map);
info.keySyms.map = NULL;
}
#ifdef XKB
if (info.xkb) XkbFreeKeyboard(info.xkb, 0, True);
#endif
return Success;
}
static void dmxProcessInputEvents(DMXInputInfo *dmxInput)
{
int i;
dmxeqProcessInputEvents();
miPointerUpdate();
if (dmxInput->detached) return;
for (i = 0; i < dmxInput->numDevs; i += dmxInput->devs[i]->binding)
if (dmxInput->devs[i]->process_input)
dmxInput->devs[i]->process_input(dmxInput->devs[i]->private);
}
static void dmxUpdateWindowInformation(DMXInputInfo *dmxInput,
DMXUpdateType type,
WindowPtr pWindow)
{
int i;
#ifdef PANORAMIX
if (!noPanoramiXExtension && pWindow && pWindow->parent != WindowTable[0])
return;
#endif
#if DMX_WINDOW_DEBUG
{
const char *name = "Unknown";
switch (type) {
case DMX_UPDATE_REALIZE: name = "Realize"; break;
case DMX_UPDATE_UNREALIZE: name = "Unrealize"; break;
case DMX_UPDATE_RESTACK: name = "Restack"; break;
case DMX_UPDATE_COPY: name = "Copy"; break;
case DMX_UPDATE_RESIZE: name = "Resize"; break;
case DMX_UPDATE_REPARENT: name = "Repaint"; break;
}
dmxLog(dmxDebug, "Window %p changed: %s\n", pWindow, name);
}
#endif
if (dmxInput->detached) return;
for (i = 0; i < dmxInput->numDevs; i += dmxInput->devs[i]->binding)
if (dmxInput->devs[i]->update_info)
dmxInput->devs[i]->update_info(dmxInput->devs[i]->private,
type, pWindow);
}
static void dmxCollectAll(DMXInputInfo *dmxInput)
{
int i;
if (dmxInput->detached) return;
for (i = 0; i < dmxInput->numDevs; i += dmxInput->devs[i]->binding)
if (dmxInput->devs[i]->collect_events)
dmxInput->devs[i]->collect_events(&dmxInput->devs[i]
->pDevice->public,
dmxMotion,
dmxEnqueue,
dmxCheckSpecialKeys, DMX_BLOCK);
}
static void dmxBlockHandler(pointer blockData, OSTimePtr pTimeout,
pointer pReadMask)
{
DMXInputInfo *dmxInput = &dmxInputs[(long)blockData];
static unsigned long generation = 0;
if (generation != serverGeneration) {
generation = serverGeneration;
dmxCollectAll(dmxInput);
}
}
static void dmxSwitchReturn(pointer p)
{
DMXInputInfo *dmxInput = p;
int i;
dmxLog(dmxInfo, "Returning from VT %d\n", dmxInput->vt_switched);
if (!dmxInput->vt_switched)
dmxLog(dmxFatal, "dmxSwitchReturn called, but not switched\n");
dmxSigioEnableInput();
for (i = 0; i < dmxInput->numDevs; i++)
if (dmxInput->devs[i]->vt_post_switch)
dmxInput->devs[i]->vt_post_switch(dmxInput->devs[i]->private);
dmxInput->vt_switched = 0;
}
static void dmxWakeupHandler(pointer blockData, int result, pointer pReadMask)
{
DMXInputInfo *dmxInput = &dmxInputs[(long)blockData];
int i;
if (dmxInput->vt_switch_pending) {
dmxLog(dmxInfo, "Switching to VT %d\n", dmxInput->vt_switch_pending);
for (i = 0; i < dmxInput->numDevs; i++)
if (dmxInput->devs[i]->vt_pre_switch)
dmxInput->devs[i]->vt_pre_switch(dmxInput->devs[i]->private);
dmxInput->vt_switched = dmxInput->vt_switch_pending;
dmxInput->vt_switch_pending = 0;
for (i = 0; i < dmxInput->numDevs; i++) {
if (dmxInput->devs[i]->vt_switch) {
dmxSigioDisableInput();
if (!dmxInput->devs[i]->vt_switch(dmxInput->devs[i]->private,
dmxInput->vt_switched,
dmxSwitchReturn,
dmxInput))
dmxSwitchReturn(dmxInput);
break; /* Only call one vt_switch routine */
}
}
}
dmxCollectAll(dmxInput);
}
static char *dmxMakeUniqueDeviceName(DMXLocalInputInfoPtr dmxLocal)
{
static int k = 0;
static int m = 0;
static int o = 0;
static unsigned long dmxGeneration = 0;
#define LEN 32
char * buf = xalloc(LEN);
if (dmxGeneration != serverGeneration) {
k = m = o = 0;
dmxGeneration = serverGeneration;
}
switch (dmxLocal->type) {
case DMX_LOCAL_KEYBOARD: XmuSnprintf(buf, LEN, "Keyboard%d", k++); break;
case DMX_LOCAL_MOUSE: XmuSnprintf(buf, LEN, "Mouse%d", m++); break;
default: XmuSnprintf(buf, LEN, "Other%d", o++); break;
}
return buf;
}
static DeviceIntPtr dmxAddDevice(DMXLocalInputInfoPtr dmxLocal)
{
DeviceIntPtr pDevice;
Atom atom;
const char *name = NULL;
void (*registerProcPtr)(DeviceIntPtr) = NULL;
char *devname;
DMXInputInfo *dmxInput;
if (!dmxLocal) return NULL;
dmxInput = &dmxInputs[dmxLocal->inputIdx];
if (dmxLocal->sendsCore) {
if (dmxLocal->type == DMX_LOCAL_KEYBOARD && !dmxLocalCoreKeyboard) {
dmxLocal->isCore = 1;
dmxLocalCoreKeyboard = dmxLocal;
name = "keyboard";
registerProcPtr = _RegisterKeyboardDevice;
}
if (dmxLocal->type == DMX_LOCAL_MOUSE && !dmxLocalCorePointer) {
dmxLocal->isCore = 1;
dmxLocalCorePointer = dmxLocal;
name = "pointer";
registerProcPtr = _RegisterPointerDevice;
}
}
#ifdef XINPUT
if (!name) {
name = "extension";
registerProcPtr = RegisterOtherDevice;
}
#else
if (!name)
dmxLog(dmxFatal,
"Server not build with XINPUT support (cannot add %s)\n",
dmxLocal->name);
#endif
if (!name || !registerProcPtr)
dmxLog(dmxFatal, "Cannot add device %s\n", dmxLocal->name);
pDevice = AddInputDevice(dmxDeviceOnOff, TRUE);
if (!pDevice) {
dmxLog(dmxError, "Too many devices -- cannot add device %s\n",
dmxLocal->name);
return NULL;
}
pDevice->public.devicePrivate = dmxLocal;
dmxLocal->pDevice = pDevice;
devname = dmxMakeUniqueDeviceName(dmxLocal);
atom = MakeAtom((char *)devname, strlen(devname), TRUE);
pDevice->type = atom;
pDevice->name = devname;
registerProcPtr(pDevice);
if (dmxLocal->isCore && dmxLocal->type == DMX_LOCAL_MOUSE)
miRegisterPointerDevice(screenInfo.screens[0], pDevice);
if (dmxLocal->create_private)
dmxLocal->private = dmxLocal->create_private(pDevice);
dmxLogInput(dmxInput, "Added %s as %s device called %s%s\n",
dmxLocal->name, name, devname,
dmxLocal->isCore
? " [core]"
: (dmxLocal->sendsCore
? " [sends core events]"
: ""));
return pDevice;
}
static DMXLocalInputInfoPtr dmxLookupLocal(const char *name)
{
DMXLocalInputInfoPtr pt;
for (pt = &DMXLocalDevices[0]; pt->name; ++pt)
if (!strcmp(pt->name, name)) return pt; /* search for device name */
return NULL;
}
/** Copy the local input information from \a s into a new \a devs slot
* in \a dmxInput. */
DMXLocalInputInfoPtr dmxInputCopyLocal(DMXInputInfo *dmxInput,
DMXLocalInputInfoPtr s)
{
DMXLocalInputInfoPtr dmxLocal = xalloc(sizeof(*dmxLocal));
if (!dmxLocal)
dmxLog(dmxFatal, "DMXLocalInputInfoPtr: out of memory\n");
memcpy(dmxLocal, s, sizeof(*dmxLocal));
dmxLocal->inputIdx = dmxInput->inputIdx;
dmxLocal->sendsCore = dmxInput->core;
dmxLocal->savedSendsCore = dmxInput->core;
dmxLocal->deviceId = -1;
++dmxInput->numDevs;
dmxInput->devs = xrealloc(dmxInput->devs,
dmxInput->numDevs * sizeof(*dmxInput->devs));
dmxInput->devs[dmxInput->numDevs-1] = dmxLocal;
return dmxLocal;
}
static void dmxPopulateLocal(DMXInputInfo *dmxInput, dmxArg a)
{
int i;
int help = 0;
DMXLocalInputInfoRec *pt;
for (i = 1; i < dmxArgC(a); i++) {
const char *name = dmxArgV(a, i);
if ((pt = dmxLookupLocal(name))) {
dmxInputCopyLocal(dmxInput, pt);
} else {
if (strlen(name))
dmxLog(dmxWarning,
"Could not find a driver called %s\n", name);
++help;
}
}
if (help) {
dmxLog(dmxInfo, "Available local device drivers:\n");
for (pt = &DMXLocalDevices[0]; pt->name; ++pt) {
const char *type;
switch (pt->type) {
case DMX_LOCAL_KEYBOARD: type = "keyboard"; break;
case DMX_LOCAL_MOUSE: type = "pointer"; break;
default: type = "unknown"; break;
}
dmxLog(dmxInfo, " %s (%s)\n", pt->name, type);
}
dmxLog(dmxFatal, "Must have valid local device driver\n");
}
}
int dmxInputExtensionErrorHandler(Display *dsp, const char *name,
const char *reason)
{
return 0;
}
static void dmxInputScanForExtensions(DMXInputInfo *dmxInput, int doXI)
{
XExtensionVersion *ext;
XDeviceInfo *devices;
Display *display;
int num;
int i, j;
DMXLocalInputInfoPtr dmxLocal;
XExtensionErrorHandler handler;
if (!(display = XOpenDisplay(dmxInput->name))) return;
/* Print out information about the XInput Extension. */
handler = XSetExtensionErrorHandler(dmxInputExtensionErrorHandler);
ext = XGetExtensionVersion(display, INAME);
XSetExtensionErrorHandler(handler);
if (!ext || ext == (XExtensionVersion *)NoSuchExtension) {
dmxLogInput(dmxInput, "%s is not available\n", INAME);
} else {
dmxLogInput(dmxInput, "Locating devices on %s (%s version %d.%d)\n",
dmxInput->name, INAME,
ext->major_version, ext->minor_version);
devices = XListInputDevices(display, &num);
XFree(ext);
ext = NULL;
/* Print a list of all devices */
for (i = 0; i < num; i++) {
const char *use = "Unknown";
switch (devices[i].use) {
case IsXPointer: use = "XPointer"; break;
case IsXKeyboard: use = "XKeyboard"; break;
case IsXExtensionDevice: use = "XExtensionDevice"; break;
}
dmxLogInput(dmxInput, " %2d %-10.10s %-16.16s\n",
devices[i].id,
devices[i].name ? devices[i].name : "",
use);
}
/* Search for extensions */
for (i = 0; i < num; i++) {
switch (devices[i].use) {
case IsXKeyboard:
for (j = 0; j < dmxInput->numDevs; j++) {
DMXLocalInputInfoPtr dmxL = dmxInput->devs[j];
if (dmxL->type == DMX_LOCAL_KEYBOARD
&& dmxL->deviceId < 0) {
dmxL->deviceId = devices[i].id;
dmxL->deviceName = (devices[i].name
? xstrdup(devices[i].name)
: NULL);
}
}
break;
case IsXPointer:
for (j = 0; j < dmxInput->numDevs; j++) {
DMXLocalInputInfoPtr dmxL = dmxInput->devs[j];
if (dmxL->type == DMX_LOCAL_MOUSE && dmxL->deviceId < 0) {
dmxL->deviceId = devices[i].id;
dmxL->deviceName = (devices[i].name
? xstrdup(devices[i].name)
: NULL);
}
}
break;
case IsXExtensionDevice:
if (doXI) {
if (!dmxInput->numDevs) {
dmxLog(dmxWarning,
"Cannot use remote (%s) XInput devices if"
" not also using core devices\n",
dmxInput->name);
} else {
dmxLocal = dmxInputCopyLocal(dmxInput,
&DMXCommonOth);
dmxLocal->isCore = FALSE;
dmxLocal->sendsCore = FALSE;
dmxLocal->deviceId = devices[i].id;
dmxLocal->deviceName = (devices[i].name
? xstrdup(devices[i].name)
: NULL);
}
}
break;
}
}
XFreeDeviceList(devices);
}
XCloseDisplay(display);
}
/** Re-initialize all the devices described in \a dmxInput. Called from
#dmxReconfig before the cursor is redisplayed. */
void dmxInputReInit(DMXInputInfo *dmxInput)
{
int i;
for (i = 0; i < dmxInput->numDevs; i++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[i];
if (dmxLocal->reinit)
dmxLocal->reinit(&dmxLocal->pDevice->public);
}
}
/** Re-initialize all the devices described in \a dmxInput. Called from
#dmxReconfig after the cursor is redisplayed. */
void dmxInputLateReInit(DMXInputInfo *dmxInput)
{
int i;
for (i = 0; i < dmxInput->numDevs; i++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[i];
if (dmxLocal->latereinit)
dmxLocal->latereinit(&dmxLocal->pDevice->public);
}
}
/** Initialize all of the devices described in \a dmxInput. */
void dmxInputInit(DMXInputInfo *dmxInput)
{
DeviceIntPtr pPointer = NULL, pKeyboard = NULL;
dmxArg a;
const char *name;
int i;
int doXI = 1; /* Include by default */
int forceConsole = 0;
int doWindows = 1; /* On by default */
int hasXkb = 0;
a = dmxArgParse(dmxInput->name);
for (i = 1; i < dmxArgC(a); i++) {
switch (hasXkb) {
case 1:
dmxInput->keycodes = xstrdup(dmxArgV(a, i));
++hasXkb;
break;
case 2:
dmxInput->symbols = xstrdup(dmxArgV(a, i));
++hasXkb;
break;
case 3:
dmxInput->geometry = xstrdup(dmxArgV(a, i));
hasXkb = 0;
break;
case 0:
if (!strcmp(dmxArgV(a, i), "noxi")) doXI = 0;
else if (!strcmp(dmxArgV(a, i), "xi")) doXI = 1;
else if (!strcmp(dmxArgV(a, i), "console")) forceConsole = 1;
else if (!strcmp(dmxArgV(a, i), "noconsole")) forceConsole = 0;
else if (!strcmp(dmxArgV(a, i), "windows")) doWindows = 1;
else if (!strcmp(dmxArgV(a, i), "nowindows")) doWindows = 0;
else if (!strcmp(dmxArgV(a, i), "xkb")) hasXkb = 1;
else {
dmxLog(dmxFatal,
"Unknown input argument: %s\n", dmxArgV(a, i));
}
}
}
name = dmxArgV(a, 0);
if (!strcmp(name, "local")) {
dmxPopulateLocal(dmxInput, a);
} else if (!strcmp(name, "dummy")) {
dmxInputCopyLocal(dmxInput, &DMXDummyMou);
dmxInputCopyLocal(dmxInput, &DMXDummyKbd);
dmxLogInput(dmxInput, "Using dummy input\n");
} else {
int found;
for (found = 0, i = 0; i < dmxNumScreens; i++) {
if (dmxPropertySameDisplay(&dmxScreens[i], name)) {
if (dmxScreens[i].shared)
dmxLog(dmxFatal,
"Cannot take input from shared backend (%s)\n",
name);
if (!dmxInput->core) {
dmxLog(dmxWarning,
"Cannot use core devices on a backend (%s)"
" as XInput devices\n", name);
} else {
char *pt;
for (pt = (char *)dmxInput->name; pt && *pt; pt++)
if (*pt == ',') *pt = '\0';
dmxInputCopyLocal(dmxInput, &DMXBackendMou);
dmxInputCopyLocal(dmxInput, &DMXBackendKbd);
dmxInput->scrnIdx = i;
dmxLogInput(dmxInput,
"Using backend input from %s\n", name);
}
++found;
break;
}
}
if (!found || forceConsole) {
char *pt;
if (found) dmxInput->console = TRUE;
for (pt = (char *)dmxInput->name; pt && *pt; pt++)
if (*pt == ',') *pt = '\0';
dmxInputCopyLocal(dmxInput, &DMXConsoleMou);
dmxInputCopyLocal(dmxInput, &DMXConsoleKbd);
if (doWindows) {
dmxInput->windows = TRUE;
dmxInput->updateWindowInfo = dmxUpdateWindowInformation;
}
dmxLogInput(dmxInput,
"Using console input from %s (%s windows)\n",
name, doWindows ? "with" : "without");
}
}
dmxArgFree(a);
/* Locate extensions we may be interested in */
dmxInputScanForExtensions(dmxInput, doXI);
for (i = 0; i < dmxInput->numDevs; i++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[i];
#ifndef XINPUT
if (!dmxLocal->isCore)
dmxLog(dmxFatal,
"This server was not compiled to support the XInput"
" extension, but %s is not a core device.\n",
dmxLocal->name);
#endif
dmxLocal->pDevice = dmxAddDevice(dmxLocal);
if (dmxLocal->isCore) {
if (dmxLocal->type == DMX_LOCAL_MOUSE)
pPointer = dmxLocal->pDevice;
if (dmxLocal->type == DMX_LOCAL_KEYBOARD)
pKeyboard = dmxLocal->pDevice;
}
}
if (pPointer && pKeyboard) {
if (dmxeqInit(&pKeyboard->public, &pPointer->public))
dmxLogInput(dmxInput, "Using %s and %s as true core devices\n",
pKeyboard->name, pPointer->name);
}
dmxInput->processInputEvents = dmxProcessInputEvents;
dmxInput->detached = False;
RegisterBlockAndWakeupHandlers(dmxBlockHandler,
dmxWakeupHandler,
(void *)(long)dmxInput->inputIdx);
}
static void dmxInputFreeLocal(DMXLocalInputInfoRec *local)
{
if (!local) return;
if (local->isCore && local->type == DMX_LOCAL_MOUSE)
dmxLocalCorePointer = NULL;
if (local->isCore && local->type == DMX_LOCAL_KEYBOARD)
dmxLocalCoreKeyboard = NULL;
if (local->destroy_private) local->destroy_private(local->private);
if (local->history) xfree(local->history);
if (local->valuators) xfree(local->valuators);
if (local->deviceName) xfree(local->deviceName);
local->private = NULL;
local->history = NULL;
local->deviceName = NULL;
xfree(local);
}
/** Free all of the memory associated with \a dmxInput */
void dmxInputFree(DMXInputInfo *dmxInput)
{
int i;
if (!dmxInput) return;
if (dmxInput->keycodes) xfree(dmxInput->keycodes);
if (dmxInput->symbols) xfree(dmxInput->symbols);
if (dmxInput->geometry) xfree(dmxInput->geometry);
for (i = 0; i < dmxInput->numDevs; i++) {
dmxInputFreeLocal(dmxInput->devs[i]);
dmxInput->devs[i] = NULL;
}
xfree(dmxInput->devs);
dmxInput->devs = NULL;
dmxInput->numDevs = 0;
if (dmxInput->freename) xfree(dmxInput->name);
dmxInput->name = NULL;
}
/** Log information about all of the known devices using #dmxLog(). */
void dmxInputLogDevices(void)
{
int i, j;
dmxLog(dmxInfo, "%d devices:\n", dmxGetInputCount());
dmxLog(dmxInfo, " Id Name Classes\n");
for (j = 0; j < dmxNumInputs; j++) {
DMXInputInfo *dmxInput = &dmxInputs[j];
const char *pt = strchr(dmxInput->name, ',');
int len = (pt
? (size_t)(pt-dmxInput->name)
: strlen(dmxInput->name));
for (i = 0; i < dmxInput->numDevs; i++) {
DeviceIntPtr pDevice = dmxInput->devs[i]->pDevice;
if (pDevice) {
dmxLog(dmxInfo, " %2d%c %-20.20s",
pDevice->id,
dmxInput->detached ? 'D' : ' ',
pDevice->name);
if (pDevice->key) dmxLogCont(dmxInfo, " key");
if (pDevice->valuator) dmxLogCont(dmxInfo, " val");
if (pDevice->button) dmxLogCont(dmxInfo, " btn");
if (pDevice->focus) dmxLogCont(dmxInfo, " foc");
if (pDevice->kbdfeed) dmxLogCont(dmxInfo, " fb/kbd");
if (pDevice->ptrfeed) dmxLogCont(dmxInfo, " fb/ptr");
if (pDevice->intfeed) dmxLogCont(dmxInfo, " fb/int");
if (pDevice->stringfeed) dmxLogCont(dmxInfo, " fb/str");
if (pDevice->bell) dmxLogCont(dmxInfo, " fb/bel");
if (pDevice->leds) dmxLogCont(dmxInfo, " fb/led");
if (!pDevice->key && !pDevice->valuator && !pDevice->button
&& !pDevice->focus && !pDevice->kbdfeed
&& !pDevice->ptrfeed && !pDevice->intfeed
&& !pDevice->stringfeed && !pDevice->bell
&& !pDevice->leds) dmxLogCont(dmxInfo, " (none)");
dmxLogCont(dmxInfo, "\t[i%d/%*.*s",
dmxInput->inputIdx, len, len, dmxInput->name);
if (dmxInput->devs[i]->deviceId >= 0)
dmxLogCont(dmxInfo, "/id%d", dmxInput->devs[i]->deviceId);
if (dmxInput->devs[i]->deviceName)
dmxLogCont(dmxInfo, "=%s", dmxInput->devs[i]->deviceName);
dmxLogCont(dmxInfo, "] %s\n",
dmxInput->devs[i]->isCore
? "core"
: (dmxInput->devs[i]->sendsCore
? "extension (sends core events)"
: "extension"));
}
}
}
}
/** Detach an input */
int dmxInputDetach(DMXInputInfo *dmxInput)
{
int i;
if (dmxInput->detached) return BadAccess;
for (i = 0; i < dmxInput->numDevs; i++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[i];
dmxLogInput(dmxInput, "Detaching device id %d: %s%s\n",
dmxLocal->pDevice->id,
dmxLocal->pDevice->name,
dmxLocal->isCore
? " [core]"
: (dmxLocal->sendsCore
? " [sends core events]"
: ""));
DisableDevice(dmxLocal->pDevice);
}
dmxInput->detached = True;
dmxInputLogDevices();
return 0;
}
/** Search for input associated with \a dmxScreen, and detach. */
void dmxInputDetachAll(DMXScreenInfo *dmxScreen)
{
int i;
for (i = 0; i < dmxNumInputs; i++) {
DMXInputInfo *dmxInput = &dmxInputs[i];
if (dmxInput->scrnIdx == dmxScreen->index) dmxInputDetach(dmxInput);
}
}
/** Search for input associated with \a deviceId, and detach. */
int dmxInputDetachId(int id)
{
DMXInputInfo *dmxInput = dmxInputLocateId(id);
if (!dmxInput) return BadValue;
return dmxInputDetach(dmxInput);
}
DMXInputInfo *dmxInputLocateId(int id)
{
int i, j;
for (i = 0; i < dmxNumInputs; i++) {
DMXInputInfo *dmxInput = &dmxInputs[i];
for (j = 0; j < dmxInput->numDevs; j++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[j];
if (dmxLocal->pDevice->id == id) return dmxInput;
}
}
return NULL;
}
static int dmxInputAttachNew(DMXInputInfo *dmxInput, int *id)
{
dmxInputInit(dmxInput);
InitAndStartDevices();
if (id && dmxInput->devs) *id = dmxInput->devs[0]->pDevice->id;
dmxInputLogDevices();
return 0;
}
static int dmxInputAttachOld(DMXInputInfo *dmxInput, int *id)
{
int i;
dmxInput->detached = False;
for (i = 0; i < dmxInput->numDevs; i++) {
DMXLocalInputInfoPtr dmxLocal = dmxInput->devs[i];
if (id) *id = dmxLocal->pDevice->id;
dmxLogInput(dmxInput,
"Attaching device id %d: %s%s\n",
dmxLocal->pDevice->id,
dmxLocal->pDevice->name,
dmxLocal->isCore
? " [core]"
: (dmxLocal->sendsCore
? " [sends core events]"
: ""));
EnableDevice(dmxLocal->pDevice);
}
dmxInputLogDevices();
return 0;
}
int dmxInputAttachConsole(const char *name, int isCore, int *id)
{
DMXInputInfo *dmxInput;
int i;
for (i = 0; i < dmxNumInputs; i++) {
dmxInput = &dmxInputs[i];
if (dmxInput->scrnIdx == -1
&& dmxInput->detached
&& !strcmp(dmxInput->name, name)) {
/* Found match */
dmxLogInput(dmxInput, "Reattaching detached console input\n");
return dmxInputAttachOld(dmxInput, id);
}
}
/* No match found */
dmxInput = dmxConfigAddInput(xstrdup(name), isCore);
dmxInput->freename = TRUE;
dmxLogInput(dmxInput, "Attaching new console input\n");
return dmxInputAttachNew(dmxInput, id);
}
int dmxInputAttachBackend(int physicalScreen, int isCore, int *id)
{
DMXInputInfo *dmxInput;
DMXScreenInfo *dmxScreen;
int i;
if (physicalScreen < 0 || physicalScreen >= dmxNumScreens) return BadValue;
for (i = 0; i < dmxNumInputs; i++) {
dmxInput = &dmxInputs[i];
if (dmxInput->scrnIdx != -1 && dmxInput->scrnIdx == physicalScreen) {
/* Found match */
if (!dmxInput->detached) return BadAccess; /* Already attached */
dmxScreen = &dmxScreens[physicalScreen];
if (!dmxScreen->beDisplay) return BadAccess; /* Screen detached */
dmxLogInput(dmxInput, "Reattaching detached backend input\n");
return dmxInputAttachOld(dmxInput, id);
}
}
/* No match found */
dmxScreen = &dmxScreens[physicalScreen];
if (!dmxScreen->beDisplay) return BadAccess; /* Screen detached */
dmxInput = dmxConfigAddInput(dmxScreen->name, isCore);
dmxLogInput(dmxInput, "Attaching new backend input\n");
return dmxInputAttachNew(dmxInput, id);
}
| 36.362654 | 99 | 0.543649 | [
"geometry"
] |
0c30d0082f258ff8d070df5414bd4b8cba1d1929 | 12,191 | c | C | extern/gtk/gtk/gtkbuilderlistitemfactory.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gtk/gtkbuilderlistitemfactory.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gtk/gtkbuilderlistitemfactory.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | /*
* Copyright © 2019 Benjamin Otte
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors: Benjamin Otte <otte@gnome.org>
*/
#include "config.h"
#include "gtkbuilderlistitemfactory.h"
#include "gtkbuilder.h"
#include "gtkbuilderprivate.h"
#include "gtkintl.h"
#include "gtklistitemfactoryprivate.h"
#include "gtklistitemprivate.h"
/**
* GtkBuilderListItemFactory:
*
* `GtkBuilderListItemFactory` is a `GtkListItemFactory` that creates
* widgets by instantiating `GtkBuilder` UI templates.
*
* The templates must be extending `GtkListItem`, and typically use
* `GtkExpression`s to obtain data from the items in the model.
*
* Example:
* ```xml
* <interface>
* <template class="GtkListItem">
* <property name="child">
* <object class="GtkLabel">
* <property name="xalign">0</property>
* <binding name="label">
* <lookup name="name" type="SettingsKey">
* <lookup name="item">GtkListItem</lookup>
* </lookup>
* </binding>
* </object>
* </property>
* </template>
* </interface>
* ```
*/
struct _GtkBuilderListItemFactory
{
GtkListItemFactory parent_instance;
GtkBuilderScope *scope;
GBytes *bytes;
GBytes *data;
char *resource;
};
struct _GtkBuilderListItemFactoryClass
{
GtkListItemFactoryClass parent_class;
};
enum {
PROP_0,
PROP_BYTES,
PROP_RESOURCE,
PROP_SCOPE,
N_PROPS
};
G_DEFINE_TYPE (GtkBuilderListItemFactory, gtk_builder_list_item_factory, GTK_TYPE_LIST_ITEM_FACTORY)
static GParamSpec *properties[N_PROPS] = { NULL, };
static void
gtk_builder_list_item_factory_setup (GtkListItemFactory *factory,
GtkListItemWidget *widget,
GtkListItem *list_item)
{
GtkBuilderListItemFactory *self = GTK_BUILDER_LIST_ITEM_FACTORY (factory);
GtkBuilder *builder;
GError *error = NULL;
GTK_LIST_ITEM_FACTORY_CLASS (gtk_builder_list_item_factory_parent_class)->setup (factory, widget, list_item);
builder = gtk_builder_new ();
gtk_builder_set_current_object (builder, G_OBJECT (list_item));
if (self->scope)
gtk_builder_set_scope (builder, self->scope);
if (!gtk_builder_extend_with_template (builder, G_OBJECT (list_item), G_OBJECT_TYPE (list_item),
(const char *)g_bytes_get_data (self->data, NULL),
g_bytes_get_size (self->data),
&error))
{
g_critical ("Error building template for list item: %s", error->message);
g_error_free (error);
/* This should never happen, if the template XML cannot be built
* then it is a critical programming error.
*/
g_object_unref (builder);
return;
}
g_object_unref (builder);
}
static void
gtk_builder_list_item_factory_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GtkBuilderListItemFactory *self = GTK_BUILDER_LIST_ITEM_FACTORY (object);
switch (property_id)
{
case PROP_BYTES:
g_value_set_boxed (value, self->bytes);
break;
case PROP_RESOURCE:
g_value_set_string (value, self->resource);
break;
case PROP_SCOPE:
g_value_set_object (value, self->scope);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static gboolean
gtk_builder_list_item_factory_set_bytes (GtkBuilderListItemFactory *self,
GBytes *bytes)
{
if (bytes == NULL)
return FALSE;
if (self->bytes)
{
g_critical ("Data for GtkBuilderListItemFactory has already been set.");
return FALSE;
}
self->bytes = g_bytes_ref (bytes);
if (!_gtk_buildable_parser_is_precompiled (g_bytes_get_data (bytes, NULL), g_bytes_get_size (bytes)))
{
GError *error = NULL;
GBytes *data;
data = _gtk_buildable_parser_precompile (g_bytes_get_data (bytes, NULL),
g_bytes_get_size (bytes),
&error);
if (data == NULL)
{
g_warning ("Failed to precompile template for GtkBuilderListItemFactory: %s", error->message);
g_error_free (error);
self->data = g_bytes_ref (bytes);
}
else
{
self->data = data;
}
}
return TRUE;
}
static void
gtk_builder_list_item_factory_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
GtkBuilderListItemFactory *self = GTK_BUILDER_LIST_ITEM_FACTORY (object);
switch (property_id)
{
case PROP_BYTES:
gtk_builder_list_item_factory_set_bytes (self, g_value_get_boxed (value));
break;
case PROP_RESOURCE:
{
GError *error = NULL;
GBytes *bytes;
const char *resource;
resource = g_value_get_string (value);
if (resource == NULL)
break;
bytes = g_resources_lookup_data (resource, 0, &error);
if (bytes)
{
if (gtk_builder_list_item_factory_set_bytes (self, bytes))
self->resource = g_strdup (resource);
g_bytes_unref (bytes);
}
else
{
g_critical ("Unable to load resource for list item template: %s", error->message);
g_error_free (error);
}
}
break;
case PROP_SCOPE:
self->scope = g_value_dup_object (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gtk_builder_list_item_factory_finalize (GObject *object)
{
GtkBuilderListItemFactory *self = GTK_BUILDER_LIST_ITEM_FACTORY (object);
g_clear_object (&self->scope);
g_bytes_unref (self->bytes);
g_bytes_unref (self->data);
g_free (self->resource);
G_OBJECT_CLASS (gtk_builder_list_item_factory_parent_class)->finalize (object);
}
static void
gtk_builder_list_item_factory_class_init (GtkBuilderListItemFactoryClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GtkListItemFactoryClass *factory_class = GTK_LIST_ITEM_FACTORY_CLASS (klass);
gobject_class->finalize = gtk_builder_list_item_factory_finalize;
gobject_class->get_property = gtk_builder_list_item_factory_get_property;
gobject_class->set_property = gtk_builder_list_item_factory_set_property;
factory_class->setup = gtk_builder_list_item_factory_setup;
/**
* GtkBuilderListItemFactory:bytes: (attributes org.gtk.Property.get=gtk_builder_list_item_factory_get_bytes)
*
* `GBytes` containing the UI definition.
*/
properties[PROP_BYTES] =
g_param_spec_boxed ("bytes",
P_("Bytes"),
P_("bytes containing the UI definition"),
G_TYPE_BYTES,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);
/**
* GtkBuilderListItemFactory:resource: (attributes org.gtk.Property.get=gtk_builder_list_item_factory_get_resource)
*
* Path of the resource containing the UI definition.
*/
properties[PROP_RESOURCE] =
g_param_spec_string ("resource",
P_("Resource"),
P_("resource containing the UI definition"),
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);
/**
* GtkBuilderListItemFactory:scope: (attributes org.gtk.Property.get=gtk_builder_list_item_factory_get_scope)
*
* `GtkBuilderScope` to use when instantiating listitems
*/
properties[PROP_SCOPE] =
g_param_spec_object ("scope",
P_("Scope"),
P_("scope to use when instantiating listitems"),
GTK_TYPE_BUILDER_SCOPE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS);
g_object_class_install_properties (gobject_class, N_PROPS, properties);
}
static void
gtk_builder_list_item_factory_init (GtkBuilderListItemFactory *self)
{
}
/**
* gtk_builder_list_item_factory_new_from_bytes:
* @scope: (nullable) (transfer none): A scope to use when instantiating
* @bytes: the `GBytes` containing the ui file to instantiate
*
* Creates a new `GtkBuilderListItemFactory` that instantiates widgets
* using @bytes as the data to pass to `GtkBuilder`.
*
* Returns: a new `GtkBuilderListItemFactory`
**/
GtkListItemFactory *
gtk_builder_list_item_factory_new_from_bytes (GtkBuilderScope *scope,
GBytes *bytes)
{
g_return_val_if_fail (bytes != NULL, NULL);
return g_object_new (GTK_TYPE_BUILDER_LIST_ITEM_FACTORY,
"bytes", bytes,
"scope", scope,
NULL);
}
/**
* gtk_builder_list_item_factory_new_from_resource:
* @scope: (nullable) (transfer none): A scope to use when instantiating
* @resource_path: valid path to a resource that contains the data
*
* Creates a new `GtkBuilderListItemFactory` that instantiates widgets
* using data read from the given @resource_path to pass to `GtkBuilder`.
*
* Returns: a new `GtkBuilderListItemFactory`
**/
GtkListItemFactory *
gtk_builder_list_item_factory_new_from_resource (GtkBuilderScope *scope,
const char *resource_path)
{
g_return_val_if_fail (scope == NULL || GTK_IS_BUILDER_SCOPE (scope), NULL);
g_return_val_if_fail (resource_path != NULL, NULL);
return g_object_new (GTK_TYPE_BUILDER_LIST_ITEM_FACTORY,
"resource", resource_path,
"scope", scope,
NULL);
}
/**
* gtk_builder_list_item_factory_get_bytes: (attributes org.gtk.Method.get_property=bytes)
* @self: a `GtkBuilderListItemFactory`
*
* Gets the data used as the `GtkBuilder` UI template for constructing
* listitems.
*
* Returns: (transfer none): The `GtkBuilder` data
*/
GBytes *
gtk_builder_list_item_factory_get_bytes (GtkBuilderListItemFactory *self)
{
g_return_val_if_fail (GTK_IS_BUILDER_LIST_ITEM_FACTORY (self), NULL);
return self->bytes;
}
/**
* gtk_builder_list_item_factory_get_resource: (attributes org.gtk.Method.get_property=resource)
* @self: a `GtkBuilderListItemFactory`
*
* If the data references a resource, gets the path of that resource.
*
* Returns: (transfer none) (nullable): The path to the resource
*/
const char *
gtk_builder_list_item_factory_get_resource (GtkBuilderListItemFactory *self)
{
g_return_val_if_fail (GTK_IS_BUILDER_LIST_ITEM_FACTORY (self), NULL);
return self->resource;
}
/**
* gtk_builder_list_item_factory_get_scope: (attributes org.gtk.Method.get_property=scope)
* @self: a `GtkBuilderListItemFactory`
*
* Gets the scope used when constructing listitems.
*
* Returns: (transfer none) (nullable): The scope used when constructing listitems
*/
GtkBuilderScope *
gtk_builder_list_item_factory_get_scope (GtkBuilderListItemFactory *self)
{
g_return_val_if_fail (GTK_IS_BUILDER_LIST_ITEM_FACTORY (self), NULL);
return self->scope;
}
| 30.630653 | 117 | 0.654417 | [
"object",
"model"
] |
0c35192f724b3ca6e0706dcd5eb13168861067ce | 882 | h | C | Libraries/graphics/Headers/graphics/Format/PNG.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 2,077 | 2016-03-02T18:28:39.000Z | 2020-12-30T06:55:17.000Z | Libraries/graphics/Headers/graphics/Format/PNG.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 235 | 2016-03-02T18:05:40.000Z | 2020-12-22T09:31:01.000Z | Libraries/graphics/Headers/graphics/Format/PNG.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 183 | 2016-03-02T19:25:10.000Z | 2020-12-24T11:05:15.000Z | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
#ifndef __graphics_Format_PNG_h
#define __graphics_Format_PNG_h
#include <graphics/Image.h>
#include <graphics/PixelFormat.h>
#include <string>
#include <utility>
#include <vector>
#include <ext/optional>
namespace graphics {
namespace Format {
/*
* Utilities for PNG images.
*/
class PNG {
private:
PNG();
~PNG();
public:
/*
* Read a PNG image.
*/
static std::pair<ext::optional<Image>, std::string>
Read(std::vector<uint8_t> const &contents);
public:
/*
* Write a PNG image.
*/
static std::pair<ext::optional<std::vector<uint8_t>>, std::string>
Write(Image const &image);
};
}
}
#endif // !__graphics_Format_PNG_h
| 17.64 | 70 | 0.675737 | [
"vector"
] |
0c3ad76a03c71e5ab2aebea05e4b3d7796534537 | 1,675 | h | C | include/trt_converter/calibrate/stream.h | smallsunsun1/trt_converter | 085cf8653894a7b9d6f75f2c220711894dce3231 | [
"MIT"
] | null | null | null | include/trt_converter/calibrate/stream.h | smallsunsun1/trt_converter | 085cf8653894a7b9d6f75f2c220711894dce3231 | [
"MIT"
] | null | null | null | include/trt_converter/calibrate/stream.h | smallsunsun1/trt_converter | 085cf8653894a7b9d6f75f2c220711894dce3231 | [
"MIT"
] | null | null | null | #ifndef INCLUDE_TRT_CONVERTER_CALIBRATE_STREAM_
#define INCLUDE_TRT_CONVERTER_CALIBRATE_STREAM_
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "NvInfer.h"
namespace sss {
class DataStreamBase {
public:
virtual void Reset(uint32_t first_batch) = 0;
virtual bool Next() = 0;
virtual void Skip(uint32_t count) = 0;
virtual std::unique_ptr<float[]> GetBatch() = 0;
virtual uint32_t GetBatchesRead() const = 0;
virtual uint32_t GetBatchSize() const = 0;
virtual nvinfer1::Dims GetDims() const = 0;
};
//
class ImageDataStream : public DataStreamBase {
public:
ImageDataStream(uint32_t batch_size, nvinfer1::Dims dims, std::vector<std::string> image_filenames)
: batch_size_(batch_size), dims_(std::move(dims)), image_filenames_(std::move(image_filenames)) {}
virtual void Reset(uint32_t first_batch) override {
current_batch = 0;
Skip(first_batch);
}
virtual bool Next() override {
if (current_batch >= image_filenames_.size()) {
return false;
}
current_batch++;
return false;
}
virtual void Skip(uint32_t count) override { current_batch += count; }
virtual std::unique_ptr<float[]> GetBatch() override;
virtual uint32_t GetBatchSize() const override { return batch_size_; }
virtual uint32_t GetBatchesRead() const override;
virtual nvinfer1::Dims GetDims() const override { return dims_; }
private:
std::vector<float> ReadImageData(const std::string& filename);
uint32_t batch_size_;
uint32_t current_batch = 0;
nvinfer1::Dims dims_;
std::vector<std::string> image_filenames_;
};
} // namespace sss
#endif /* INCLUDE_TRT_CONVERTER_CALIBRATE_STREAM_ */
| 29.385965 | 104 | 0.73194 | [
"vector"
] |
0c4499010aab5ec6d36a6dbb29ff869bea2d3b95 | 19,377 | c | C | src/kernel/i386-kos/posix_signals.c | GrieferAtWork/KOS | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 2 | 2017-02-24T17:14:19.000Z | 2017-10-12T19:26:13.000Z | src/kernel/i386-kos/posix_signals.c | GrieferAtWork/KOS | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 1 | 2019-11-02T10:21:11.000Z | 2019-11-02T10:21:11.000Z | src/kernel/i386-kos/posix_signals.c | GabrielRavier/KOSmk3 | 5376a813854b35e3a3532a6e3b8dbb168478b40f | [
"Zlib"
] | 1 | 2019-11-02T10:20:19.000Z | 2019-11-02T10:20:19.000Z | /* Copyright (c) 2018 Griefer@Work *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
*/
#ifndef GUARD_KERNEL_I386_KOS_POSIX_SIGNALS_C
#define GUARD_KERNEL_I386_KOS_POSIX_SIGNALS_C 1
#define _KOS_SOURCE 1
#include <hybrid/compiler.h>
#include <kos/types.h>
#include <kos/i386-kos/asm/pf-syscall.h>
#include <bits/sigaction.h>
#include <i386-kos/posix_signals.h>
#include <i386-kos/fpu.h>
#include <i386-kos/gdt.h>
#include <kernel/user.h>
#include <kernel/debug.h>
#include <kernel/vm.h>
#include <kernel/syscall.h>
#include <kos/context.h>
#include <kos/intrin.h>
#include <kos/registers.h>
#include <sched/task.h>
#include <sched/posix_signals.h>
#include <sched/task.h>
#include <sched/userstack.h>
#include <sched/pid.h>
#include <assert.h>
#include <string.h>
#include <sys/ucontext.h>
#include <asm/cpu-flags.h>
#include <syscall.h>
#include <except.h>
#include "posix_signals.h"
DECL_BEGIN
INTDEF ATTR_NORETURN void (KCALL throw_invalid_segment)(u16 segment_index, u16 segment_register);
#define throw_invalid_segment(segment_index,segment_register) \
__EXCEPT_INVOKE_THROW_NORETURN(throw_invalid_segment(segment_index,segment_register))
INTERN void KCALL
x86_sigreturn_impl(void *UNUSED(arg),
struct cpu_hostcontext_user *__restrict context,
unsigned int UNUSED(mode)) {
struct cpu_hostcontext_user *EXCEPT_VAR xcontext = context;
struct signal_frame *frame;
unsigned int frame_mode;
assertf(context->c_iret.ir_cs & 3,"sigreturn() invoked from kernel-space");
/* At this point, `context->c_psp' points after the
* `sf_sigreturn' field of a signal frame structure. */
frame = (struct signal_frame *)(context->c_psp -
COMPILER_OFFSETAFTER(struct signal_frame,sf_sigreturn));
validate_readable(frame,sizeof(*frame));
/* Let's get to the restoring part of this all!
* NOTE: User-space register sanitization _must_ be done _after_ we copied register
* values, and must be performed on the values then saved in `context'! */
COMPILER_READ_BARRIER();
#ifndef __x86_64__
memcpy(&context->c_gpregs,&frame->sf_return.m_context.c_gpregs,
sizeof(struct x86_gpregs32)+sizeof(struct x86_segments32));
#else /* !__x86_64__ */
memcpy(&context->c_gpregs,&frame->sf_return.m_context.c_gpregs,
sizeof(struct x86_gpregs32));
#endif /* __x86_64__ */
#ifndef CONFIG_X86_FIXED_SEGMENTATION
context->c_iret.ir_cs = frame->sf_return.m_context.c_cs;
context->c_iret.ir_ss = frame->sf_return.m_context.c_ss;
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
context->c_iret.ir_pflags = frame->sf_return.m_context.c_pflags;
context->c_iret.ir_pip = frame->sf_return.m_context.c_pip;
#ifdef __x86_64__
context->c_iret.ir_rsp = context->c_rsp;
#else
context->c_iret.ir_useresp = context->c_gpregs.gp_esp;
#endif
frame_mode = frame->sf_mode;
if (PERTASK_TESTF(this_task.t_flags,TASK_FOWNUSERSEG|TASK_FUSEREXCEPT) &&
frame->sf_except.e_context.c_pip != (uintptr_t)-1) {
/* Copy user-space exception information. */
USER CHECKED struct user_task_segment *useg;
useg = PERTASK_GET(this_task.t_userseg);
validate_readable(&useg->ts_self,sizeof(useg->ts_self));
useg = useg->ts_self;
validate_writable(&useg->ts_xcurrent,sizeof(useg->ts_xcurrent));
/* Restore user-space exception information during a regular sigreturn().
* This behavior is by `EXCEPTIONS AND POSIX SIGNAL HANDLERS' in `<except.h>' */
memcpy(&useg->ts_xcurrent,&frame->sf_except,sizeof(struct user_exception_info));
}
#ifndef CONFIG_NO_FPU
if (frame->sf_return.m_flags & __MCONTEXT_FHAVEFPU) {
/* Restore the saved FPU state. */
x86_fpu_alloc();
COMPILER_BARRIER();
memcpy(PERTASK_GET(x86_fpu_context),
&frame->sf_return.m_fpu,
sizeof(struct fpu_context));
COMPILER_BARRIER();
x86_fpu_load();
} else {
/* Reset the FPU state. */
x86_fpu_reset();
}
#endif /* !CONFIG_NO_FPU */
#ifdef __x86_64__
/* Set user-space segment pointers. */
WR_USER_FSBASE(frame->sf_return.m_context.c_segments.sg_fsbase);
WR_USER_GSBASE(frame->sf_return.m_context.c_segments.sg_gsbase);
#endif
COMPILER_READ_BARRIER();
/* Sanitize the new user-space register state. */
context->c_iret.ir_pflags |= (EFLAGS_IF);
context->c_iret.ir_pflags &= ~(EFLAGS_TF|EFLAGS_IOPL(3)|
EFLAGS_NT|EFLAGS_RF|EFLAGS_VM|
EFLAGS_AC|EFLAGS_VIF|EFLAGS_VIP|
EFLAGS_ID);
/* Verify user-space segment indices. */
TRY {
#ifndef __x86_64__
#ifndef CONFIG_X86_FIXED_SEGMENTATION
if (context->c_segments.sg_ds && !__verw(context->c_segments.sg_ds))
throw_invalid_segment(context->c_segments.sg_ds,X86_REGISTER_SEGMENT_DS);
if (context->c_segments.sg_es && !__verw(context->c_segments.sg_es))
throw_invalid_segment(context->c_segments.sg_es,X86_REGISTER_SEGMENT_ES);
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
if (context->c_segments.sg_fs && !__verw(context->c_segments.sg_fs))
throw_invalid_segment(context->c_segments.sg_fs,X86_REGISTER_SEGMENT_FS);
if (context->c_segments.sg_gs && !__verw(context->c_segments.sg_gs))
throw_invalid_segment(context->c_segments.sg_gs,X86_REGISTER_SEGMENT_GS);
#endif /* !__x86_64__ */
#ifndef CONFIG_X86_FIXED_SEGMENTATION
if (context->c_iret.ir_ss && !__verw(context->c_iret.ir_ss))
throw_invalid_segment(context->c_iret.ir_ss,X86_REGISTER_SEGMENT_SS);
/* Ensure ring #3 (This is _highly_ important. Without this,
* user-space would be executed as kernel-code; autsch...) */
if ((context->c_iret.ir_cs & 3) != 3 || !__verr(context->c_iret.ir_cs))
throw_invalid_segment(context->c_iret.ir_cs,X86_REGISTER_SEGMENT_CS);
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
} EXCEPT (EXCEPT_EXECUTE_HANDLER) {
/* Must fix register values, as otherwise userspace wouldn't be able to handle the exception. */
#ifndef __x86_64__
#ifndef CONFIG_X86_FIXED_SEGMENTATION
if (xcontext->c_segments.sg_ds && !__verw(xcontext->c_segments.sg_ds))
xcontext->c_segments.sg_ds = X86_SEG_USER_DS;
if (xcontext->c_segments.sg_es && !__verw(xcontext->c_segments.sg_es))
xcontext->c_segments.sg_es = X86_SEG_USER_ES;
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
if (xcontext->c_segments.sg_fs && !__verw(xcontext->c_segments.sg_fs))
xcontext->c_segments.sg_fs = X86_SEG_USER_FS;
if (xcontext->c_segments.sg_gs && !__verw(xcontext->c_segments.sg_gs))
xcontext->c_segments.sg_gs = X86_SEG_USER_GS;
#endif /* !__x86_64__ */
#ifndef CONFIG_X86_FIXED_SEGMENTATION
if (xcontext->c_iret.ir_ss && !__verw(xcontext->c_iret.ir_ss))
xcontext->c_iret.ir_ss = X86_SEG_USER_SS;
if ((xcontext->c_iret.ir_cs & 3) != 3 || !__verr(xcontext->c_iret.ir_cs))
xcontext->c_iret.ir_cs = X86_SEG_USER_CS;
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
error_rethrow();
}
COMPILER_BARRIER();
/* Restore the saved signal mask. */
signal_chmask(&frame->sf_sigmask,NULL,
sizeof(sigset_t),
SIGNAL_CHMASK_FSETMASK);
#if 0
debug_printf("SIGRETURN:%d\n",frame_mode);
#endif
/* Determine how to return to user-space / resume execution. */
switch (TASK_USERCTX_TYPE(frame_mode)) {
case TASK_USERCTX_TYPE_WITHINUSERCODE:
error_info()->e_error.e_code = E_USER_RESUME;
break;
case TASK_USERCTX_TYPE_INTR_INTERRUPT:
error_throw(E_INTERRUPT);
break;
{
syscall_ulong_t EXCEPT_VAR sysno;
syscall_ulong_t EXCEPT_VAR orig_pax;
syscall_ulong_t EXCEPT_VAR orig_pip;
syscall_ulong_t EXCEPT_VAR orig_pbp;
syscall_ulong_t EXCEPT_VAR orig_pdi;
syscall_ulong_t EXCEPT_VAR orig_psp;
case TASK_USERCTX_TYPE_INTR_SYSCALL:
/* Restart an interrupted system call by executing it now. */
orig_pax = context->c_gpregs.gp_pax;
orig_pip = context->c_pip;
orig_pbp = context->c_gpregs.gp_pbp;
orig_pdi = context->c_gpregs.gp_pdi;
#ifdef __x86_64__
orig_psp = context->c_iret.ir_rsp;
#else
orig_psp = context->c_iret.ir_useresp;
#endif
restart_sigframe_syscall:
TRY {
/* Convert the user-space register context to become `int $0x80'-compatible */
switch (frame_mode & TASK_USERCTX_REGS_FMASK) {
{
syscall_ulong_t masked_sysno;
u8 argc;
case TASK_USERCTX_REGS_FSYSENTER:
argc = 6;
sysno = xcontext->c_gpregs.gp_pax;
masked_sysno = sysno & ~0x80000000;
xcontext->c_pip = orig_pdi; /* CLEANUP: return.%eip = %edi */
#ifdef __x86_64__
xcontext->c_iret.ir_rsp = orig_pbp; /* CLEANUP: return.%esp = %ebp */
#else
xcontext->c_iret.ir_useresp = orig_pbp; /* CLEANUP: return.%esp = %ebp */
#endif
/* Figure out how many arguments this syscall takes. */
if (masked_sysno <= __NR_syscall_max)
argc = x86_syscall_argc[masked_sysno];
else if (masked_sysno >= __NR_xsyscall_min &&
masked_sysno <= __NR_xsyscall_max) {
argc = x86_xsyscall_argc[masked_sysno-__NR_xsyscall_min];
}
/* Load additional arguments from user-space. */
if (argc >= 4)
xcontext->c_gpregs.gp_pdi = *((u32 *)(orig_pbp + 0));
if (argc >= 5)
xcontext->c_gpregs.gp_pbp = *((u32 *)(orig_pbp + 4));
COMPILER_READ_BARRIER();
} break;
case TASK_USERCTX_REGS_FPF:
sysno = xcontext->c_pip - PERTASK_GET(x86_sysbase);
sysno = X86_DECODE_PFSYSCALL(sysno);
xcontext->c_pip = xcontext->c_gpregs.gp_pax; /* #PF uses EAX as return address. */
xcontext->c_gpregs.gp_pax = sysno; /* #PF encodes the sysno in EIP. */
break;
default:
sysno = xcontext->c_gpregs.gp_pax;
break;
}
#if 0
debug_printf("\n\n"
"Restart system call after signal (%p)\n"
"\n\n",
sysno);
#endif
/* Actually execute the system call (using the `int $0x80'-compatible register set). */
x86_syscall_exec80();
} EXCEPT (EXCEPT_EXECUTE_HANDLER) {
/* Set the FSYSCALL flag so that exceptions are propagated accordingly. */
error_info()->e_error.e_flag |= X86_INTERRUPT_GUARD_FSYSCALL;
if (error_code() == E_INTERRUPT) {
/* Restore the original user-space CPU xcontext. */
xcontext->c_gpregs.gp_pax = orig_pax;
xcontext->c_pip = orig_pip;
xcontext->c_gpregs.gp_pbp = orig_pbp;
xcontext->c_gpregs.gp_pdi = orig_pdi;
#ifdef __x86_64__
xcontext->c_iret.ir_rsp = orig_psp;
#else
xcontext->c_iret.ir_useresp = orig_psp;
#endif
COMPILER_WRITE_BARRIER();
/* Deal with system call restarts. */
task_restart_syscall(xcontext,
TASK_USERCTX_TYPE_WITHINUSERCODE|
TASK_USERCTX_REGS_FPF,
sysno);
COMPILER_BARRIER();
goto restart_sigframe_syscall;
}
error_rethrow();
}
} break;
default: break;
}
}
DEFINE_SYSCALL_DONTRESTART(sigreturn);
DEFINE_SYSCALL0(sigreturn) {
/* Use an RPC callback to gain access to the user-space register state. */
task_queue_rpc_user(THIS_TASK,
&x86_sigreturn_impl,
NULL,
TASK_RPC_USER);
return 0;
}
/* Redirect the given user-space context to call a signal
* handler `action' before actually returning to user-space. */
PUBLIC void KCALL
arch_posix_signals_redirect_action(struct cpu_hostcontext_user *__restrict context,
siginfo_t const *__restrict info,
struct sigaction const *__restrict action,
unsigned int mode) {
struct signal_frame *frame;
validate_executable(action->sa_handler);
#if 0
debug_printf("REDIRECT_ACTION %u:%p -> %p\n",
posix_gettid(),
context->c_pip,
action->sa_handler);
#endif
if (action->sa_flags & SA_SIGINFO) {
struct userstack *stack = PERTASK_GET(_this_user_stack);
struct signal_frame_ex *xframe;
xframe = (struct signal_frame_ex *)context->c_psp-1;
validate_writable(xframe,sizeof(*xframe));
frame = &xframe->sf_frame;
#ifndef __x86_64__
xframe->sf_infop = &xframe->sf_info;
xframe->sf_contextp = &xframe->sf_return;
#endif
/* Fill in extended-signal-frame-specific fields. */
memcpy(&xframe->sf_info,info,sizeof(siginfo_t));
if (stack) {
xframe->sf_return.uc_stack.ss_sp = (void *)VM_PAGE2ADDR(stack->us_pagemin);
xframe->sf_return.uc_stack.ss_size = VM_PAGES2SIZE(stack->us_pageend-stack->us_pagemin);
xframe->sf_return.uc_stack.ss_flags = SS_ONSTACK;
} else {
xframe->sf_return.uc_stack.ss_sp = (void *)context->c_psp;
xframe->sf_return.uc_stack.ss_size = 1;
xframe->sf_return.uc_stack.ss_flags = SS_DISABLE;
}
xframe->sf_return.uc_link = NULL;
} else {
frame = (struct signal_frame *)context->c_psp-1;
validate_writable(frame,sizeof(*frame));
}
{
/* Copy the signal-blocking-set to-be applied upon return. */
struct sigblock *block = PERTASK_GET(_this_sigblock);
if (!block)
memset(&frame->sf_sigmask,0,sizeof(sigset_t));
else {
memcpy(&frame->sf_sigmask,&block->sb_sigset,sizeof(sigset_t));
}
}
if (PERTASK_TESTF(this_task.t_flags,TASK_FOWNUSERSEG|TASK_FUSEREXCEPT)) {
/* Copy user-space exception information. */
USER CHECKED struct user_task_segment *useg;
useg = PERTASK_GET(this_task.t_userseg);
validate_readable(&useg->ts_self,sizeof(useg->ts_self));
useg = useg->ts_self;
validate_readable(&useg->ts_xcurrent,sizeof(useg->ts_xcurrent));
memcpy(&frame->sf_except,&useg->ts_xcurrent,sizeof(struct user_exception_info));
} else {
/* sys_sigreturn() uses the exception context EIP
* value to identify the presence of a context. */
frame->sf_except.e_context.c_pip = (uintptr_t)-1;
}
/* Construct the return CPU context. */
#ifdef __x86_64__
memcpy(&frame->sf_return.m_context.c_gpregs,
&context->c_gpregs,sizeof(struct x86_gpregs));
#ifdef CONFIG_X86_FIXED_SEGMENTATION
frame->sf_return.m_context.c_rflags = context->c_iret.ir_rflags;
frame->sf_return.m_context.c_rip = context->c_iret.ir_rip;
frame->sf_return.m_context.c_rsp = context->c_iret.ir_rsp;
#else /* CONFIG_X86_FIXED_SEGMENTATION */
memcpy(&frame->sf_return.m_context.c_iret,
&context->c_iret,sizeof(struct x86_irregs64));
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
frame->sf_return.m_context.c_segments.sg_fsbase = RD_USER_FSBASE();
frame->sf_return.m_context.c_segments.sg_gsbase = RD_USER_GSBASE();
#else
memcpy(&frame->sf_return.m_context.c_segments,
&context->c_segments,sizeof(struct x86_segments));
frame->sf_return.m_context.c_gpregs.gp_edi = context->c_gpregs.gp_edi;
frame->sf_return.m_context.c_gpregs.gp_esi = context->c_gpregs.gp_esi;
frame->sf_return.m_context.c_gpregs.gp_ebp = context->c_gpregs.gp_ebp;
frame->sf_return.m_context.c_gpregs.gp_esp = context->c_iret.ir_useresp;
frame->sf_return.m_context.c_gpregs.gp_ebx = context->c_gpregs.gp_ebx;
frame->sf_return.m_context.c_gpregs.gp_edx = context->c_gpregs.gp_edx;
frame->sf_return.m_context.c_gpregs.gp_ecx = context->c_gpregs.gp_ecx;
frame->sf_return.m_context.c_gpregs.gp_eax = context->c_gpregs.gp_eax;
frame->sf_return.m_context.c_eip = context->c_eip;
frame->sf_return.m_context.c_eflags = context->c_eflags;
#ifndef CONFIG_X86_FIXED_SEGMENTATION
frame->sf_return.m_context.c_cs = context->c_iret.ir_cs;
frame->sf_return.m_context.c_ss = context->c_iret.ir_ss;
#endif /* !CONFIG_X86_FIXED_SEGMENTATION */
#endif
frame->sf_return.m_flags = __MCONTEXT_FNORMAL;
if (info->si_signo == SIGSEGV) {
frame->sf_return.m_cr2 = (uintptr_t)info->si_addr;
frame->sf_return.m_flags |= __MCONTEXT_FHAVECR2;
}
#ifndef CONFIG_NO_FPU
if (x86_fpu_save()) {
memcpy(&frame->sf_return.m_fpu,
PERTASK_GET(x86_fpu_context),
sizeof(struct fpu_context));
frame->sf_return.m_flags |= __MCONTEXT_FHAVEFPU;
}
#endif
#ifdef __x86_64__
context->c_gpregs.gp_rdi = info->si_signo; /* Arg #1 */
if (action->sa_flags & SA_SIGINFO) {
struct signal_frame_ex *xframe;
xframe = (struct signal_frame_ex *)frame;
context->c_gpregs.gp_rsi = (u64)&xframe->sf_info; /* Arg #2 */
context->c_gpregs.gp_rdx = (u64)&xframe->sf_return; /* Arg #3 */
}
#else
frame->sf_signo = info->si_signo;
#endif
/* Redirect the frame's sig-return pointer to direct it at the `sys_sigreturn' system call.
* Being able to do this right here is the main reason why #PF-syscalls were introduced. */
if (TASK_USERCTX_TYPE(mode) == TASK_USERCTX_TYPE_INTR_SYSCALL) {
syscall_ulong_t sysno = context->c_gpregs.gp_pax;
if (mode & TASK_USERCTX_REGS_FPF) {
/* Deal with #PF system calls. */
sysno = (uintptr_t)context->c_pip-PERTASK_GET(x86_sysbase);
sysno = X86_DECODE_PFSYSCALL(sysno);
}
if (should_restart_syscall(sysno,
(action->sa_flags&SA_RESTART)
? (SHOULD_RESTART_SYSCALL_FPOSIX_SIGNAL|
SHOULD_RESTART_SYSCALL_FSA_RESTART)
: (SHOULD_RESTART_SYSCALL_FPOSIX_SIGNAL))) {
/* Setup the signal frame to restart the system
* call once `sys_sigreturn()' is executed. */
frame->sf_mode = mode;
} else {
/* Throw E_INTERRUPT, or return `-EINTR' from the system call that got interrupted. */
frame->sf_mode = TASK_USERCTX_TYPE_INTR_INTERRUPT;
}
if (!(sysno & 0x80000000))
goto sigreturn_noexcept;
/* Set the exceptions-enabled bit in the system call vector number. */
frame->sf_sigreturn = (void *)(PERTASK_GET(x86_sysbase)+
X86_ENCODE_PFSYSCALL(SYS_sigreturn|0x80000000));
} else {
/* Resume execution in user-space normally. */
frame->sf_mode = TASK_USERCTX_TYPE_WITHINUSERCODE;
sigreturn_noexcept:
frame->sf_sigreturn = (void *)(PERTASK_GET(x86_sysbase)+
X86_ENCODE_PFSYSCALL(SYS_sigreturn));
}
/* With the signal frame now generated, update context registers to execute the signal action. */
context->c_psp = (uintptr_t)frame;
context->c_pip = (uintptr_t)action->sa_handler;
/* Resume user-space by executing the signal handler. */
error_info()->e_error.e_code = E_USER_RESUME;
}
DECL_END
#endif /* !GUARD_KERNEL_I386_KOS_POSIX_SIGNALS_C */
| 39.384146 | 98 | 0.694586 | [
"vector"
] |
bd08e03371c5a88ef03d4af4295388a2ee1150f8 | 44,434 | c | C | src/readability.c | xtkoba/rdrview | 9bde19f9e53562790b363bb2e3b15707c8c67676 | [
"Apache-2.0"
] | 714 | 2020-10-12T21:20:25.000Z | 2022-03-10T14:53:02.000Z | src/readability.c | xtkoba/rdrview | 9bde19f9e53562790b363bb2e3b15707c8c67676 | [
"Apache-2.0"
] | 25 | 2020-10-15T03:13:52.000Z | 2022-03-14T16:59:42.000Z | src/readability.c | xtkoba/rdrview | 9bde19f9e53562790b363bb2e3b15707c8c67676 | [
"Apache-2.0"
] | 33 | 2020-10-19T06:03:49.000Z | 2022-03-07T01:37:32.000Z | /*
* Implementation of parse(), which tries to extract an article from the HTML
*
* Copyright (C) 2020 Ernesto A. Fernández <ernesto.mnd.fernandez@gmail.com>
*
* Based on Mozilla's Readability.js, available at:
* https://github.com/mozilla/readability/
* Original copyright notice:
*
* Copyright (c) 2010 Arc90 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ctype.h>
#include <string.h>
#include <libxml/tree.h>
#include <libxml/uri.h>
#include "rdrview.h"
struct metadata metadata = {0};
/* List of previous attempts to get the content */
struct attempt {
htmlNodePtr article;
int length;
};
static struct attempt attempts[4] = {0};
/**
* Is there a better title than the current one under the name or property of
* this meta tag?
*/
static bool is_better_title(char *nameprop)
{
static const char * const titlenames[] = {
"dc:title", "dcterm:title", "og:title", "weibo:article:title",
"weibo:webpage:title", "title", "twitter:title"
};
static unsigned int best_i = ARRAY_SIZE(titlenames);
unsigned int i;
for (i = 0; i < ARRAY_SIZE(titlenames); ++i) {
if (i <= best_i && word_in_str(nameprop, titlenames[i])) {
best_i = i;
return true;
}
}
return false;
}
/**
* Is there a better byline than the current one under the name or property of
* this meta tag?
*/
static bool is_better_byline(char *nameprop)
{
static const char * const authornames[] = {
"dc:creator", "dcterm:creator", "author"
};
static unsigned int best_i = ARRAY_SIZE(authornames);
unsigned int i;
for (i = 0; i < ARRAY_SIZE(authornames); ++i) {
if (i <= best_i && word_in_str(nameprop, authornames[i])) {
best_i = i;
return true;
}
}
return false;
}
/**
* Is there a better excerpt than the current one under the name or property of
* this meta tag?
*/
static bool is_better_excerpt(char *nameprop)
{
static const char * const excerptnames[] = {
"dc:description", "dcterm:description", "og:description",
"weibo:article:description", "weibo:webpage:description",
"description", "twitter:description"
};
static unsigned int best_i = ARRAY_SIZE(excerptnames);
unsigned int i;
for (i = 0; i < ARRAY_SIZE(excerptnames); ++i) {
if (i <= best_i && word_in_str(nameprop, excerptnames[i])) {
best_i = i;
return true;
}
}
return false;
}
/**
* Extract a metadata field from the content of a name or property meta tag
*
* TODO: apparently a single property tag can have multiple contents?
*/
static void parse_meta_attrs(char *nameprop, char *content)
{
char **field = NULL;
if (!*content)
return;
replace_char(nameprop, '.', ':');
field = &metadata.title;
if (is_better_title(nameprop))
goto copy;
field = &metadata.byline;
if (is_better_byline(nameprop))
goto copy;
field = &metadata.excerpt;
if (is_better_excerpt(nameprop))
goto copy;
field = &metadata.site_name;
if (word_in_str(nameprop, "og:site_name"))
goto copy;
return;
copy:
if (*field)
free(*field);
*field = malloc(strlen(content) + 1);
if (!*field)
fatal_errno();
strcpy_normalize((xmlChar *)*field, (xmlChar *)content);
}
/**
* Is this node a heading containing the given string?
*/
static bool is_heading_with_str(htmlNodePtr node, const void *str)
{
xmlChar *content;
bool ret;
if (!node_has_tag(node, "h1", "h2"))
return false;
content = node_get_normalized_content(node);
if (!content)
return false;
ret = strcmp(str, (char *)content) == 0; /* TODO: trimming? */
xmlFree(content);
return ret;
}
/**
* Get the title for the article from the title tag
* TODO: this function is still missing some stuff from the firefox version
*/
static char *get_article_title(htmlDocPtr doc, htmlNodePtr titlenode)
{
char *title, *original;
int title_count, orig_count;
char *sep;
title = (char *)node_get_normalized_content(titlenode);
original = strdup(title);
sep = find_last_separator(title);
if (sep) {
*(sep - 1) = '\0';
} else {
char *substr, *copy;
substr = strrchr(title, ':');
/*
* fx: Check if we have an heading containing this exact string, so we
* could assume it's the full title.
*/
if (substr && such_node_exists(doc, is_heading_with_str, title))
goto out;
if (substr) {
copy = strdup(substr + 1);
xmlFree(title);
title = copy;
}
}
title_count = word_count(title, false /* separators_are_spaces */);
orig_count = word_count(original, true /* separators are spaces */);
if (title_count <= 4 && (!sep || title_count != orig_count - 1)) {
free(title);
title = original;
}
out:
if (title != original)
free(original);
return title;
}
/**
* If this is a metadata node, extract and remember the metadata. Return NULL,
* except for the title node: in that case return the node.
*/
static void *node_extract_metadata(htmlNodePtr node)
{
xmlChar *name = NULL;
xmlChar *property = NULL;
xmlChar *content = NULL;
if (node_has_tag(node, "title"))
return node;
if (!node_has_tag(node, "meta"))
return NULL;
content = xmlGetProp(node, (xmlChar *)"content");
if (!content)
goto out;
property = xmlGetProp(node, (xmlChar *)"property");
if (regex_matches(&property_re, property)) {
parse_meta_attrs((char *)property, (char *)content);
goto out;
}
name = xmlGetProp(node, (xmlChar *)"name");
if (regex_matches(&name_re, name))
parse_meta_attrs((char *)name, (char *)content);
out:
xmlFree(name);
xmlFree(property);
xmlFree(content);
return NULL;
}
/**
* fx: Attempts to get excerpt and byline metadata for the article.
*/
static void get_article_metadata(htmlDocPtr doc)
{
htmlNodePtr titlenode = NULL;
titlenode = run_on_nodes(doc, node_extract_metadata);
if (!metadata.title && titlenode)
metadata.title = get_article_title(doc, titlenode);
}
/**
* Check if this node has the byline and, if it does, remember the value
*/
static bool check_byline(htmlNodePtr node)
{
static bool found_byline;
xmlChar *itemprop = NULL;
xmlChar *class = NULL;
xmlChar *id = NULL;
bool is_byline = true;
if (found_byline)
return false;
if (attrcmp(node, "rel", "author"))
goto out;
itemprop = xmlGetProp(node, (xmlChar *)"itemprop");
if (itemprop && strstr((char *)itemprop, "author"))
goto out;
class = xmlGetProp(node, (xmlChar *)"class");
id = xmlGetProp(node, (xmlChar *)"id");
if (regex_matches(&byline_re, class) || regex_matches(&byline_re, id))
goto out;
is_byline = false;
out:
if (is_byline) {
int len = text_content_length(node);
if (len > 0 && len < 100) { /* Is this a sane byline? */
if (!metadata.byline)
metadata.byline = (char *)node_get_normalized_content(node);
found_byline = true;
}
}
xmlFree(itemprop);
xmlFree(class);
xmlFree(id);
return found_byline;
}
/**
* Is this node unlikely to be readable?
*/
static bool is_node_unlikely(htmlNodePtr node)
{
if (attrcmp(node, "role", "complementary"))
return true;
if (has_ancestor_tag(node, "table") || node_has_tag(node, "body", "a"))
return false;
return node_has_unlikely_class_id(node);
}
/**
* If this node is an element, is it a break element?
*/
static bool is_break_if_element(htmlNodePtr node)
{
if (node->type != XML_ELEMENT_NODE)
return true;
return node_has_tag(node, "br", "hr");
}
/**
* Is this node an empty element?
*/
static bool is_element_without_content(htmlNodePtr node)
{
if (node->type != XML_ELEMENT_NODE || text_content_length(node))
return false;
return forall_descendants(node, is_break_if_element);
}
static const char * const DIV_ELEMS[] = {
"div", "section", "header", "h1", "h2", "h3", "h4", "h5", "h6",
};
/**
* Is this a DIV, SECTION or HEADER node without any content?
*/
static bool is_division_without_content(htmlNodePtr node)
{
if (!node_has_tag_array(node, ARRAY_SIZE(DIV_ELEMS), DIV_ELEMS))
return false;
return is_element_without_content(node);
}
/**
* Is this node white space?
*/
static bool is_whitespace(htmlNodePtr node)
{
if (xmlNodeIsText(node) && !text_content_length(node))
return true;
return node_has_tag(node, "br");
}
/**
* Remove all trailing children that are just whitespace
*/
static void prune_trailing_whitespace(htmlNodePtr node)
{
htmlNodePtr child = xmlGetLastChild(node);
while (child && is_whitespace(child)) {
htmlNodePtr prev = child->prev;
xmlUnlinkNode(child);
free_node(child);
child = prev;
}
}
/**
* Reparent a node to a preceding "p" sibling; if the sibling is NULL, create
* it. Return the new parent for the node, or NULL if no reparenting happened.
*/
static htmlNodePtr reparent_to_p_sibling(htmlNodePtr node, htmlNodePtr sibling)
{
if (!sibling) {
if (is_whitespace(node))
return NULL; /* Don't start a paragraph for whitespace alone */
sibling = xmlNewNode(NULL, (xmlChar *)"p");
if (!sibling || !xmlAddPrevSibling(node, sibling))
fatal();
}
xmlUnlinkNode(node);
if (!xmlAddChild(sibling, node))
fatal();
return sibling;
}
static const char * const DIV_TO_P_ELEMS[] = {
"a", "blockquote", "dl", "div", "img", "ol", "p", "pre", "table", "ul",
"select",
};
/**
* Is this node a block level element?
*/
static bool is_block_element(htmlNodePtr node)
{
static const int tagc = ARRAY_SIZE(DIV_TO_P_ELEMS);
if (node->type != XML_ELEMENT_NODE)
return false;
return node_has_tag_array(node, tagc, DIV_TO_P_ELEMS);
}
/**
* Handle a div node for grab_article() and return the next node to process
*/
static htmlNodePtr handle_div_node_for_grab(htmlNodePtr node)
{
htmlNodePtr parag = NULL;
htmlNodePtr child;
/* fx: Put phrasing content into paragraphs */
for (child = node->children; child; child = child->next) {
if (is_phrasing_content(child)) {
parag = reparent_to_p_sibling(child, parag);
if (parag)
child = parag;
} else if (parag) {
prune_trailing_whitespace(parag);
parag = NULL;
}
}
/*
* fx: Sites like http://mobile.slate.com encloses each paragraph with a
* DIV element. DIVs with only a P element inside and no text content can
* be safely converted into plain P elements to avoid confusing the scoring
* algorithm with DIVs with are, in practice, paragraphs.
*/
if (has_single_tag_inside(node, "p") && get_link_density(node) < 0.25) {
htmlNodePtr child = xmlFirstElementChild(node);
if (!child)
fatal();
xmlReplaceNode(node, child);
free_node(node);
node = child;
mark_to_score(node);
} else if (!has_such_descendant(node, is_block_element)) {
xmlNodeSetName(node, (xmlChar *)"p");
mark_to_score(node);
}
return following_node(node);
}
static const char * const TAGS_TO_SCORE[] = {
"section", "h2", "h3", "h4", "h5", "h6", "p", "td", "pre",
};
/**
* Is this node's tag one of those that need to be scored by default?
*/
static inline bool has_default_tag_to_score(htmlNodePtr node)
{
return node_has_tag_array(node, ARRAY_SIZE(TAGS_TO_SCORE), TAGS_TO_SCORE);
}
/**
* Do we know for sure that we won't need to score this node?
*
* This function may have the side-effect of setting the byline.
*/
static bool no_need_to_score(htmlNodePtr node)
{
if (!is_node_visible(node))
return true;
if (check_byline(node))
return true;
if ((options.flags & OPT_STRIP_UNLIKELY) && is_node_unlikely(node))
return true;
/*
* fx: Remove DIV, SECTION, and HEADER nodes without any content
* (e.g. text, image, video, or iframe).
*/
return is_division_without_content(node);
}
/**
* Initialize a node with a preliminary readability score.
*/
void initialize_node(htmlNodePtr node)
{
if (node_has_tag(node, "div"))
add_to_score(node, +5);
else if (node_has_tag(node, "pre", "td", "blockquote"))
add_to_score(node, +3);
else if (node_has_tag(node, "address", "form"))
add_to_score(node, -3);
else if (node_has_tag(node, "ol", "ul", "dl", "dd", "dt", "li"))
add_to_score(node, -3);
else if (node_has_tag(node, "h1", "h2", "h3", "h4", "h5", "h6", "th"))
add_to_score(node, -5);
add_to_score(node, get_class_weight(node));
mark_as_initialized(node);
}
/**
* fx: Initialize and score ancestors
*/
static void assign_content_score_ancestors(htmlNodePtr node, int score)
{
int level = 3; /* Only score 3 ancestors */
for (node = node->parent; node && level; node = node->parent, level--) {
if (!node->name)
continue;
if (!node->parent || node->parent->type != XML_ELEMENT_NODE)
continue;
if (!is_initialized(node)) {
initialize_node(node);
mark_as_candidate(node);
}
switch (level) {
case 3:
add_to_score(node, score);
break;
case 2:
add_to_score(node, score / 2.0);
break;
case 1:
add_to_score(node, score / 6.0);
break;
}
}
}
/**
* fx: assign a score to them based on how content-y they look. Then add their
* score to their parent node. A score is determined by things like number of
* commas, class names, etc. Maybe eventually link density.
*/
static void *assign_content_score(htmlNodePtr node)
{
xmlChar *text = NULL;
int length;
int score = 0;
if (!is_to_score(node))
goto out;
if (!node->parent || node->parent->type != XML_ELEMENT_NODE)
goto out;
text = node_get_normalized_content(node);
length = text ? xmlUTF8Strlen(text) : 0;
if (length < 25)
goto out;
++score; /* fx: Add a point for the paragraph itself as a base. */
score += char_count((char *)text, ',') + 1; /* fx: points for commas */
/*
* fx: For every 100 characters in this paragraph, add another point.
* Up to 3 points.
*/
score += MIN(length / 100, 3);
/* fx: Initialize and score ancestors */
assign_content_score_ancestors(node, score);
out:
xmlFree(text);
return NULL;
}
/*
* fx: Because of our bonus system, parents of candidates might have scores
* themselves. They get half of the node. There won't be nodes with higher
* scores than our topCandidate, but if we see the score going *up* in the
* first few steps up the tree, that's a decent sign that there might be more
* content lurking in other places that we want to unify in. The sibling stuff
* below does some of that - but only if we've looked high enough up the DOM
* tree.
*/
static htmlNodePtr find_ancestor_with_more_content(htmlNodePtr node)
{
htmlNodePtr ancestor;
double lastscore = load_score(node);
double score_threshold = lastscore / 3.0;
for (ancestor = node->parent; ancestor; ancestor = ancestor->parent) {
double ancestor_score;
if (node_has_tag(ancestor, "body"))
break;
ancestor_score = load_score(ancestor);
if (!ancestor_score)
continue;
if (ancestor_score < score_threshold)
break; /* fx: The scores shouldn't get too low */
if (ancestor_score > lastscore)
return ancestor; /* fx: Alright! We found a better parent to use */
lastscore = load_score(ancestor);
}
return node;
}
/**
* Is 'n1' an ancestor of 'n2'?
*/
static bool is_ancestor_of(htmlNodePtr n1, htmlNodePtr n2)
{
while (n2) {
if (n2 == n1)
return true;
n2 = n2->parent;
}
return false;
}
/*
* fx: The number of top candidates to consider when analysing how tight the
* competition is among candidates. TODO: override through cli option?
*/
#define DEFAULT_N_TOP_CANDIDATES 5
/**
* Search for a better top candidate among the ancestors of the current one
*/
static htmlNodePtr find_better_top_candidate(htmlNodePtr *tops)
{
htmlNodePtr topnode = tops[0];
double topscore = load_score(topnode);
htmlNodePtr ancestor;
int i;
if (!topscore)
return topnode; /* Avoid division by zero */
/*
* fx: Find a better top candidate node if it contains (at least three) node
* which belong to `topCandidates` array and whose scores are quite closed
* with current `topCandidate` node.
*/
for (ancestor = topnode->parent; ancestor; ancestor = ancestor->parent) {
static const int MINIMUM_TOPCANDIDATES = 3;
int contained_tops = 0;
if (node_has_tag(ancestor, "body"))
break;
for (i = 1; i < DEFAULT_N_TOP_CANDIDATES && tops[i]; i++) {
if (load_score(tops[i]) / topscore < 0.75)
continue;
if (!is_ancestor_of(ancestor, tops[i]))
continue;
++contained_tops;
}
if (contained_tops >= MINIMUM_TOPCANDIDATES) {
topnode = ancestor;
break;
}
}
if (!is_initialized(topnode))
initialize_node(topnode);
topnode = find_ancestor_with_more_content(topnode);
/*
* fx: If the top candidate is the only child, use parent instead. This
* will help sibling joining logic when adjacent content is actually
* located in parent's sibling node.
*/
while (xmlChildElementCount(topnode->parent) == 1) {
if (!topnode->parent || node_has_tag(topnode->parent, "body"))
break;
topnode = topnode->parent;
}
if (!is_initialized(topnode))
initialize_node(topnode);
return topnode;
}
/**
* Return the top candidate list, updated if appropriate to include the node
*/
static void *consider_for_top_list(htmlNodePtr node)
{
static htmlNodePtr tops[DEFAULT_N_TOP_CANDIDATES] = {0};
double score;
int i;
if (!is_candidate(node))
return tops;
score = load_score(node) * (1 - get_link_density(node));
save_score(node, score);
for (i = 0; i < DEFAULT_N_TOP_CANDIDATES; ++i) {
int remaining;
if (tops[i] && score <= load_score(tops[i]))
continue;
/* Make room for the new node among the top ones */
remaining = DEFAULT_N_TOP_CANDIDATES - i - 1;
memmove(&tops[i + 1], &tops[i], remaining * sizeof(*tops));
tops[i] = node;
break;
}
return tops;
}
/**
* fx: After we've calculated scores, loop through all of the possible
* candidate nodes we found and find the one with the highest score.
*/
static htmlNodePtr find_top_candidate(htmlDocPtr doc)
{
htmlNodePtr *tops = run_on_nodes(doc, consider_for_top_list);
htmlNodePtr result;
if (!tops)
return NULL;
if (!tops[0] || node_has_tag(tops[0], "body"))
result = NULL;
else
result = find_better_top_candidate(tops);
tops[0] = NULL; /* Static array: mark as empty so that it can be reused */
return result;
}
/**
* Get the body node for the document
*/
static htmlNodePtr get_body(htmlDocPtr doc)
{
htmlNodePtr root = xmlDocGetRootElement(doc);
htmlNodePtr child;
for (child = root->children; child; child = child->next) {
if (node_has_tag(child, "body"))
return child;
}
fatal_msg("document has no body tag");
}
/**
* fx: If we still have no top candidate, just use the body as a last resort.
* We also have to copy the body node so it is something we can modify.
*/
static htmlNodePtr top_candidate_from_all(htmlDocPtr doc)
{
htmlNodePtr body = get_body(doc);
htmlNodePtr new, child, next;
new = xmlNewNode(NULL, (xmlChar *)"div");
if (!new)
fatal();
for (child = body->children; child; child = next) {
next = child->next;
xmlUnlinkNode(child);
if (!xmlAddChild(new, child))
fatal();
}
if (!xmlAddChild(body, new))
fatal();
initialize_node(new);
return new;
}
/**
* Append a node to the content node for the document
*/
static void append_content(htmlNodePtr content, htmlNodePtr node)
{
static const char * const to_div_exc[] = {"div", "article", "section", "p"};
if (!node_has_tag_array(node, ARRAY_SIZE(to_div_exc), to_div_exc)) {
/*
* fx: We have a node that isn't a common block level element, like a
* form or td tag. Turn it into a div so it doesn't get filtered out
* later by accident.
*/
xmlNodeSetName(node, (xmlChar *)"div");
}
xmlUnlinkNode(node);
if (!xmlAddChild(content, node))
fatal();
}
/**
* Is this node a paragraph with content?
*/
static bool is_paragraph_with_content(htmlNodePtr node)
{
double link_density;
xmlChar *content;
int length;
bool ret;
if (!node_has_tag(node, "p"))
return false;
content = node_get_normalized_content(node);
if (!content)
return false;
length = strlen((char *)content);
link_density = get_link_density(node);
ret = true;
if (length > 80 && link_density < 0.25)
goto out;
if (link_density == 0 && regex_matches(&sentence_dot_re, content))
goto out;
ret = false;
out:
xmlFree(content);
return ret;
}
/**
* fx: Now that we have the top candidate, look through its siblings for
* content that might also be related. Things like preambles, content split
* by ads that we removed, etc.
*/
static htmlNodePtr gather_related_content(htmlNodePtr top)
{
htmlNodePtr parent = top->parent;
double topscore = load_score(top);
double score_threshold = MAX(topscore * 0.2, 10.0);
htmlNodePtr child, next;
htmlNodePtr content;
xmlChar *topclass;
content = xmlNewNode(NULL, (xmlChar *)"div");
if (!content)
fatal();
topclass = xmlGetProp(top, (xmlChar *)"class");
for (child = parent->children; child; child = next) {
double score;
double content_bonus = 0;
xmlChar *class;
next = child->next; /* The child may get unlinked at some point */
if (child == top) {
append_content(content, child);
continue;
}
/*
* fx: Give a bonus if sibling nodes and top candidates have the
* example same classname
*/
class = xmlGetProp(child, (xmlChar *)"class");
if (class && topclass)
if (*class && strcasecmp((char *)class, (char *)topclass) == 0)
content_bonus = topscore * 0.2;
xmlFree(class);
score = load_score(child);
if (is_initialized(child) && score + content_bonus >= score_threshold) {
append_content(content, child);
continue;
}
if (is_paragraph_with_content(child))
append_content(content, child);
}
xmlFree(topclass);
return content;
}
/**
* Set on this node the attributes expected for the main div of the article
*/
static void set_main_div_attrs(htmlNodePtr div)
{
xmlSetProp(div, (xmlChar *)"id", (xmlChar *)"readability-page-1");
xmlSetProp(div, (xmlChar *)"class", (xmlChar *)"page");
}
/**
* Create a single main div for the given article
*/
static void create_main_div(htmlNodePtr article)
{
htmlNodePtr div, child, next;
div = xmlNewNode(NULL, (xmlChar *)"div");
if (!div)
fatal();
set_main_div_attrs(div);
for (child = article->children; child; child = next) {
next = child->next;
xmlUnlinkNode(child);
xmlAddChild(div, child);
}
xmlAddChild(article, div);
}
/**
* Save an extracted article in the list of previous attempts
*/
static void save_attempt(htmlNodePtr article, int article_len)
{
struct attempt *slot;
for (slot = &attempts[0]; slot != &attempts[4]; ++slot) {
if (slot->article)
continue;
slot->article = article;
slot->length = article_len;
return;
}
assert(false);
}
/**
* Do we need to keep working on extracting the contents? If true, save the
* current attempt and tweak the flags for the next one.
*/
static bool needs_one_more_try(htmlNodePtr article)
{
int article_len = text_normalized_content_length(article);
/*
* fx: Now that we've gone through the full algorithm, check to see if we
* got any meaningful content. If we didn't, we may need to re-run
* grabArticle with different flags set. This gives us a higher likelihood
* of finding the content, and the sieve approach gives us a higher
* likelihood of finding the -right- content.
*/
save_attempt(article, article_len);
if (article_len >= DEFAULT_CHAR_THRESHOLD)
return false;
if (options.flags & OPT_STRIP_UNLIKELY)
options.flags ^= OPT_STRIP_UNLIKELY;
else if (options.flags & OPT_WEIGHT_CLASSES)
options.flags ^= OPT_WEIGHT_CLASSES;
else if (options.flags & OPT_CLEAN_CONDITIONALLY)
options.flags ^= OPT_CLEAN_CONDITIONALLY;
else
return false;
return true;
}
/**
* Free all articles in the attempt list except for the best one that is given
*/
static void free_attempts_except(htmlNodePtr best)
{
struct attempt *slot;
for (slot = &attempts[0]; slot != &attempts[4]; ++slot) {
if (slot->article != best)
free_node(slot->article);
}
}
/**
* Return the best extraction attempt, or NULL if all were a failure
*/
static htmlNodePtr get_best_attempt(void)
{
htmlNodePtr article = NULL;
struct attempt *slot, *best;
/* fx: just return the longest text we found during the different loops */
best = &attempts[0];
for (slot = &attempts[1]; slot != &attempts[4]; ++slot) {
if (slot->length <= best->length)
continue;
best = slot;
}
if (best->length) /* fx: But first check if we actually have something */
article = best->article;
return article;
}
/**
* fx: Find out text direction from ancestors of final top candidate
*
* The given parent is the actual parent of the node in the original html, not
* its current parent inside the extracted article.
*/
static void extract_text_direction(htmlNodePtr node, htmlNodePtr parent)
{
htmlNodePtr ancestor = node;
xmlChar *direction = NULL;
while (ancestor && !direction) {
if (ancestor->name)
direction = xmlGetProp(ancestor, (xmlChar *)"dir");
ancestor = (ancestor == node) ? parent : ancestor->parent;
}
if (!direction)
return;
metadata.direction = malloc(strlen((char *)direction) + 1);
if (!metadata.direction)
fatal_errno();
strcpy(metadata.direction, (char *)direction);
xmlFree(direction);
}
/**
* fx: Using a variety of metrics (content score, classname, element types),
* find the content that is most likely to be the stuff a user wants to read.
* Then return it wrapped up in a div.
*/
static htmlNodePtr grab_article(htmlDocPtr doc)
{
htmlNodePtr node, top, top_parent, article;
htmlDocPtr tempdoc = NULL;
do {
bool top_is_new = false;
/* We may got through several attempts, so preserve the original doc */
free_doc(tempdoc);
tempdoc = xmlCopyDoc(doc, 1 /* recursive */);
if (!tempdoc)
fatal();
node = first_node(tempdoc);
while (node) {
if (no_need_to_score(node)) {
node = remove_and_get_following(node);
continue;
}
if (has_default_tag_to_score(node))
mark_to_score(node);
/*
* fx: Turn all divs that don't have children block level elements
* into p's
*/
if (node_has_tag(node, "div")) {
node = handle_div_node_for_grab(node);
continue;
}
node = following_node(node);
}
run_on_nodes(tempdoc, assign_content_score);
top = find_top_candidate(tempdoc);
if (!top) {
top = top_candidate_from_all(tempdoc);
top_is_new = true;
}
top_parent = top->parent; /* Save this before unlinking top */
article = gather_related_content(top);
/*
* fx: So we have all of the content that we need. Now we clean it up
* for presentation.
*/
prep_article(article);
if (!article->children) /* Even the top candidate is gone */
continue;
if (top_is_new) /* fx: we already created a fake div thing... */
set_main_div_attrs(top);
else
create_main_div(article);
} while (needs_one_more_try(article));
article = get_best_attempt();
if (article)
extract_text_direction(top, top_parent);
free_attempts_except(article);
free_doc(tempdoc);
return article;
}
/**
* Is this node an image placeholder?
*/
static bool is_image_placeholder(htmlNodePtr node)
{
xmlAttrPtr attr;
if (!node_has_tag(node, "img"))
return false;
for (attr = node->properties; attr; attr = attr->next) {
char *name = (char *)attr->name;
xmlChar *value;
bool is_match;
if (strcmp(name, "src") == 0 || strcmp(name, "srcset") == 0)
return false;
if (strcmp(name, "data-src") == 0 || strcmp(name, "data-srcset") == 0)
return false;
value = xmlGetProp(node, attr->name);
is_match = regex_matches(&imgext_re, value);
xmlFree(value);
if (is_match)
return false;
}
return true;
}
/**
* fx: Check if node is image, or if node contains exactly only one image
* whether as a direct child or as its descendants.
*
* Our version returns the image node directly, or NULL if the check failed.
*/
static htmlNodePtr get_single_image(htmlNodePtr node)
{
if (node_has_tag(node, "img"))
return node;
while (node) {
htmlNodePtr child, elem_child = NULL;
child = node->children;
for (child = node->children; child; child = child->next) {
if (child->type == XML_ELEMENT_NODE) {
if (elem_child)
return NULL;
elem_child = child;
} else if (text_normalized_content_length(child)) {
return NULL;
}
}
if (node_has_tag(elem_child, "img"))
return elem_child;
node = elem_child;
}
return NULL;
}
/**
* Could this attribute contain an image?
*/
static bool is_image_attr(const xmlChar *name, const xmlChar *value)
{
if (!value || !*value)
return false;
if (strcasecmp((char *)name, "src") == 0)
return true;
if (strcasecmp((char *)name, "srcset") == 0)
return true;
if (regex_matches(&imgext_re, value))
return true;
return false;
}
/**
* Copy attributes of an image element that might contain an image; preserve
* those that already exist in the destination.
*/
static void copy_image_attrs(htmlNodePtr dest, htmlNodePtr src)
{
xmlAttrPtr attr;
for (attr = src->properties; attr; attr = attr->next) {
xmlChar *srcval = NULL, *destval = NULL;
xmlChar *backup_name = NULL;
srcval = xmlGetProp(src, attr->name);
if (!is_image_attr(attr->name, srcval))
goto next;
destval = xmlGetProp(dest, attr->name);
if (!destval) {
xmlSetProp(dest, attr->name, srcval);
goto next;
}
if (xmlStrcmp(destval, srcval) == 0)
goto next;
/*
* This attribute already exists in the destination, but copy the
* source value anyway, under a different name.
*/
backup_name = xmlMalloc(1);
if (!backup_name)
fatal_errno();
*backup_name = '\0';
backup_name = xmlStrcat(backup_name, (xmlChar *)"data-old-");
backup_name = xmlStrcat(backup_name, attr->name);
xmlSetProp(dest, backup_name, srcval);
xmlFree(backup_name);
next:
xmlFree(destval);
xmlFree(srcval);
}
}
/**
* If the node is a noscript element with a single image inside, try to use it
* to replace a previous image.
*/
static void *unwrap_if_noscript_image(htmlNodePtr node)
{
htmlNodePtr prev, newimg, oldimg;
if (!node_has_tag(node, "noscript"))
return NULL;
newimg = get_single_image(node);
if (!newimg)
return NULL;
prev = prev_element(node);
if (!prev)
return NULL;
oldimg = get_single_image(prev);
if (!oldimg)
return NULL;
/*
* fx: If noscript has previous sibling and it only contains image, replace
* it with noscript content. However we also keep old attributes that might
* contains image.
*/
copy_image_attrs(newimg, oldimg);
xmlReplaceNode(prev, newimg);
free_node(prev);
return NULL;
}
/**
* fx: Find all <noscript> that are located after <img> nodes, and which
* contain only one <img> element. Replace the first image with the image
* from inside the <noscript> tag, and remove the <noscript> tag. This
* improves the quality of the images we use on some sites (e.g. Medium).
*/
static void unwrap_noscript_images(htmlDocPtr doc)
{
/*
* fx: Find img without source or attributes that might contains image,
* and remove it. This is done to prevent a placeholder img is replaced
* by img from noscript in next step.
*/
remove_nodes_if(doc, is_image_placeholder);
run_on_nodes(doc, unwrap_if_noscript_image);
}
/**
* Is this a script or noscript node?
*/
static bool is_script_or_noscript(htmlNodePtr node)
{
if (node_has_tag(node, "noscript"))
return true;
if (node_has_tag(node, "script")) {
xmlAttrPtr src = xmlHasProp(node, (xmlChar *)"src");
/* I don't see how this is necessary at all, but just follow firefox */
if (src && xmlRemoveProp(src) < 0)
fatal();
xmlNodeSetContent(node, (xmlChar *)"");
return true;
}
return false;
}
/**
* Is this node the first <br> in a <br><br> sequence?
*/
static bool is_double_br(htmlNodePtr node)
{
return node_has_tag(node, "br") && node_has_tag(next_element(node), "br");
}
/**
* fx: Replaces 2 or more successive <br> elements with a single <p>.
* Whitespace between <br> elements are ignored. For example:
* <div>foo<br>bar<br> <br><br>abc</div>
* will become:
* <div>foo<br>bar<p>abc</p></div>
*/
static void *replace_brs(htmlNodePtr node)
{
htmlNodePtr next;
bool replaced = false;
if (!node_has_tag(node, "br"))
return NULL;
for (next = next_element(node); next; next = next_element(node)) {
if (!node_has_tag(next, "br"))
break;
replaced = true;
xmlUnlinkNode(next);
free_node(next);
}
if (!replaced)
return NULL;
xmlNodeSetName(node, (xmlChar *)"p");
for (next = node->next; next; next = node->next) {
/*
* fx: If we've hit another <br><br>, we're done adding children
* to this <p>.
*/
if (is_double_br(next) || !is_phrasing_content(next))
break;
/* fx: make this node a child of the new <p> */
xmlUnlinkNode(next);
if (!xmlAddChild(node, next))
fatal();
}
prune_trailing_whitespace(node);
if (node_has_tag(node->parent, "p"))
xmlNodeSetName(node->parent, (xmlChar *)"div");
return NULL;
}
/**
* fx: Prepare the HTML document for readability to scrape it. This includes
* things like stripping javascript [sic], CSS, and handling terrible markup.
*/
static void prep_document(htmlDocPtr doc)
{
htmlNodePtr node = first_node(doc);
while (node) {
if (node_has_tag(node, "style")) {
node = remove_and_get_following(node);
} else if (node_has_tag(node, "font")) {
xmlNodeSetName(node, (xmlChar *)"span");
node = following_node(node);
} else {
node = following_node(node);
}
}
run_on_nodes(doc, replace_brs);
}
/**
* Replace a relative URL with its absolute version
*/
static void to_absolute_url(xmlChar **url)
{
xmlChar *original = *url;
xmlChar *result;
size_t i;
/* fx: Leave hash links alone if the base URI matches the document URI */
if (!(options.flags & OPT_URL_OVERRIDE) && original[0] == '#')
return;
/* Trailing whitespace in the URL seems to confuse libxml2 */
i = strlen((char *)original);
while (i--) {
if (!isspace(original[i]))
break;
original[i] = '\0';
}
result = xmlBuildURI(original, (xmlChar *)options.base_url);
if (!result)
return;
xmlFree(original);
*url = result;
}
/**
* Remove a node but preserve its children in the same location; return a
* pointer to this new node.
*/
static htmlNodePtr remove_but_preserve_content(htmlNodePtr node)
{
htmlNodePtr child = node->children;
htmlNodePtr next;
htmlNodePtr new;
/*
* fx: if the link only contains simple text content, it can be converted
* to a text node
*/
if (child && !child->next && xmlNodeIsText(child)) {
xmlChar *content;
content = xmlNodeGetContent(child);
new = xmlNewText(content);
xmlFree(content);
goto replace;
}
/* fx: if the link has multiple children, they should all be preserved */
new = xmlNewNode(NULL, (xmlChar *)"span");
for (child = node->children; child; child = next) {
next = child->next;
xmlUnlinkNode(child);
if (!xmlAddChild(new, child))
fatal();
}
replace:
xmlReplaceNode(node, new);
free_node(node);
return new;
}
/**
* If the node is a link, get rid of any relative or javascript URLs. If this
* involves replacing the node altogether, return the new node in its location.
*/
static htmlNodePtr fix_non_absolute_link(htmlNodePtr node)
{
xmlChar *href = NULL;
if (!node_has_tag(node, "a"))
goto out;
href = xmlGetProp(node, (xmlChar *)"href");
if (!href)
goto out;
if (xmlStrcasestr(href, (xmlChar *)"javascript:")) {
/* fx: Remove links with javascript: URIs */
node = remove_but_preserve_content(node);
goto out;
}
to_absolute_url(&href);
xmlSetProp(node, (xmlChar *)"href", href);
out:
xmlFree(href);
return node;
}
struct srcset_entry {
char *url;
char *size;
};
/**
* Parse a single item from a srcset into the url and size buffers; return the
* length of the item, or 0 on failure.
*/
static int parse_srcset_item(const char *srcset, char *url, char *size)
{
const char *start = srcset;
int i;
url[0] = size[0] = '\0';
for (; isspace(*srcset); ++srcset);
for (i = 0; *srcset && !isspace(*srcset); ++srcset, ++i)
url[i] = *srcset;
if (i == 0)
return 0;
if (url[i - 1] == ',') {
url[i - 1] = '\0';
return srcset - start;
}
url[i] = '\0';
for (; isspace(*srcset); ++srcset);
/* If a srcset item has a size, it doesn't need a space after the comma */
for (i = 0; *srcset && *srcset != ','; ++srcset, ++i)
size[i] = *srcset;
size[i] = '\0';
if (*srcset == ',')
++srcset;
return srcset - start;
}
/**
* Parse a srcset property into an array of srcset_entry structs
*/
static struct srcset_entry *parse_srcset(const char *srcset)
{
size_t len = strlen(srcset) + 1;
struct srcset_entry *ents;
int url_bound, i;
/* Only an upper bound, because there might be commas inside the URLs */
url_bound = char_count(srcset, ',') + 1;
/* The extra NULL entry at the end acts as a terminator */
ents = calloc(url_bound + 1, sizeof(*ents));
for (i = 0; i < url_bound; ++i) {
char *url, *size;
int ret;
/* Again, extremely coarse upper bounds */
url = malloc(len);
size = malloc(len);
if (!url || !size)
fatal();
ret = parse_srcset_item(srcset, url, size);
if (!ret) {
free(url);
free(size);
break;
}
ents[i].url = url;
ents[i].size = size;
srcset += ret;
}
return ents;
}
/**
* Replace relative with absolute URLs in an array of srcset_entry structs
*/
static void to_absolute_srcset_entries(struct srcset_entry *ents)
{
while (ents->url) {
to_absolute_url((xmlChar **)&ents->url);
++ents;
}
}
/**
* Assemble a srcset property from an array of srcset_entry structs
*/
static char *build_srcset(struct srcset_entry *ents)
{
struct srcset_entry *curr;
char *srcset;
size_t len = 0;
/* Find the length for the new srcset */
curr = ents;
while (curr->url) {
size_t url_len, sizelen;
url_len = strlen(curr->url);
sizelen = curr->size ? strlen(curr->size) : 0;
if (url_len > 4096 || sizelen > 4096)
break;
len += url_len + sizelen + 3; /* Two spaces and a comma */
++curr;
}
len += 1; /* The null termination */
srcset = malloc(len);
if (!srcset)
fatal_errno();
srcset[0] = '\0';
/* Now get it assembled */
curr = ents;
while (curr->url) {
if (curr != ents)
strcat(srcset, ", ");
strcat(srcset, curr->url);
if (*curr->size) {
strcat(srcset, " ");
strcat(srcset, curr->size);
}
++curr;
}
return srcset;
}
/**
* Clean up an array of srcset_entry structs
*/
static void free_srcset(struct srcset_entry *ents)
{
struct srcset_entry *curr = ents;
while (curr->url) {
free(curr->url);
free(curr->size);
++curr;
}
free(ents);
}
/**
* Convert all relative URLs in a srcset to absolute URLs
*/
static void to_absolute_srcset(xmlChar **srcset_p)
{
struct srcset_entry *ents;
ents = parse_srcset((char *)*srcset_p);
to_absolute_srcset_entries(ents);
xmlFree(*srcset_p);
*srcset_p = (xmlChar *)build_srcset(ents);
free_srcset(ents);
}
static const char * const MEDIA_ELEMS[] = {
"img", "picture", "figure", "video", "audio", "source",
};
/**
* If the node is a media element, convert it to an absolute URL
*/
static htmlNodePtr fix_relative_media(htmlNodePtr node)
{
xmlChar *urls;
if (!node_has_tag_array(node, ARRAY_SIZE(MEDIA_ELEMS), MEDIA_ELEMS))
return node;
urls = xmlGetProp(node, (xmlChar *)"src");
if (urls) {
to_absolute_url(&urls);
xmlSetProp(node, (xmlChar *)"src", urls);
xmlFree(urls);
}
urls = xmlGetProp(node, (xmlChar *)"poster");
if (urls) {
to_absolute_url(&urls);
xmlSetProp(node, (xmlChar *)"poster", urls);
xmlFree(urls);
}
urls = xmlGetProp(node, (xmlChar *)"srcset");
if (urls) {
to_absolute_srcset(&urls);
xmlSetProp(node, (xmlChar *)"srcset", urls);
xmlFree(urls);
}
return node;
}
/**
* fx: Converts each <a> and <img> uri in the given element to an absolute URI,
* ignoring #ref URIs.
*
* TODO: add a cli option to preserve the relative URLs
*/
static void fix_all_relative_urls(htmlNodePtr article)
{
change_descendants(article, fix_non_absolute_link);
change_descendants(article, fix_relative_media);
}
/**
* fx: Removes the class="" attribute [...], except those that match
* CLASSES_TO_PRESERVE and the classesToPreserve array from the options object.
*
* TODO: add cli option to preserve other classes, or all of them
*/
static htmlNodePtr clean_classes(htmlNodePtr node)
{
xmlChar *class_list;
char *class;
class_list = xmlGetProp(node, (xmlChar *)"class");
if (!class_list)
return node;
class = strtok((char *)class_list, " ");
while (class) {
if (strcmp((char *)class, "page") == 0) /* Set by ourselves */
break;
class = strtok(NULL, " ");
}
if (class) /* The node has the page class */
xmlSetProp(node, (xmlChar *)"class", (xmlChar *)"page");
else
xmlUnsetProp(node, (xmlChar *)"class");
xmlFree(class_list);
return node;
}
/**
* If this is a text node, normalize it
*/
static htmlNodePtr clean_if_text_node(htmlNodePtr node)
{
/*
* libxml2 will indent tags even inside preformatted blocks, so get
* rid of the inner tag entirely.
*/
if (node_has_tag(node, "code") && node_has_tag(node->parent, "pre")) {
htmlNodePtr parent = node->parent;
xmlReplaceNode(parent, node);
free_node(parent);
xmlNodeSetName(node, (xmlChar *)"pre");
} else if (xmlNodeIsText(node)) {
xmlChar *content = node_get_normalized_or_preformatted(node);
xmlNodeSetContent(node, content);
xmlFree(content);
}
return node;
}
/**
* If the document provides a base URL, set it in the global options
*/
void set_base_url_from_doc(htmlDocPtr doc)
{
xmlChar *meta_url;
meta_url = xmlGetProp(first_node_with_tag(doc, "base"), (xmlChar *)"href");
if (!meta_url)
return;
to_absolute_url(&meta_url);
options.base_url = (char *)meta_url;
options.flags |= OPT_URL_OVERRIDE;
}
/**
* Is the node a comment?
*/
static bool is_comment(htmlNodePtr node)
{
return node->type == XML_COMMENT_NODE;
}
/**
* Put an empty text node inside this element if it's not allowed to be
* self-closing, otherwise libxml2 will make it so.
*
* We only focus on the elements that caused actual problems in our tests,
* others can be added later if needed.
*/
static htmlNodePtr fill_if_not_self_closing(htmlNodePtr node)
{
if (node_has_tag(node, "iframe", "em", "a") && !node->children)
xmlNodeSetContent(node, (xmlChar *)" ");
return node;
}
/**
* Get rid of the siblings for the document's root node
*/
static void remove_root_siblings(htmlDocPtr doc)
{
htmlNodePtr root = xmlDocGetRootElement(doc);
htmlNodePtr sib;
assert(root);
for (sib = root->next; sib; sib = root->next) {
xmlUnlinkNode(sib);
free_node(sib);
}
for (sib = root->prev; sib; sib = root->prev) {
xmlUnlinkNode(sib);
free_node(sib);
}
}
/**
* Extract the content from an article's first paragraph
*/
static char *first_paragraph_content(htmlNodePtr article)
{
htmlNodePtr node = first_descendant_with_tag(article, "p");
return (char *)node_get_normalized_content(node);
}
/**
* Clean up the extracted metadata for presentation
*/
static void clean_metadata(void)
{
trim_and_unescape(&metadata.title);
trim_and_unescape(&metadata.byline);
trim_and_unescape(&metadata.excerpt);
trim_and_unescape(&metadata.site_name);
}
/**
* fx: Runs readability.
*
* Workflow:
* 1. Prep the document by removing script tags, css, etc.
* 2. Build readability's DOM tree.
* 3. Grab the article content from the current dom tree.
* 4. Replace the current DOM tree with the new one.
* 5. Read peacefully.
*/
htmlNodePtr parse(htmlDocPtr doc)
{
htmlNodePtr article, content;
if (!xmlDocGetRootElement(doc))
return NULL;
/* Do this early to prevent problems when traversing the tree */
remove_root_siblings(doc);
set_base_url_from_doc(doc);
remove_nodes_if(doc, is_comment);
unwrap_noscript_images(doc);
remove_nodes_if(doc, is_script_or_noscript);
prep_document(doc);
get_article_metadata(doc);
article = grab_article(doc);
if (!article)
return NULL;
fix_all_relative_urls(article);
change_descendants(article, clean_classes);
change_descendants(article, clean_if_text_node);
/* We wouldn't need this if we could print/save a single node as html */
change_descendants(article, fill_if_not_self_closing);
if (!metadata.excerpt)
metadata.excerpt = first_paragraph_content(article);
clean_metadata();
/* Discard the wrapping div */
content = article->children;
xmlUnlinkNode(content);
free_node(article);
return content;
}
| 24.070423 | 79 | 0.687447 | [
"object"
] |
bd0ee8ba2d34f854b7264dc5b617ee7a84c99b09 | 5,327 | h | C | camera/hal/usb/metadata_handler.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/hal/usb/metadata_handler.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/hal/usb/metadata_handler.h | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2016 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef CAMERA_HAL_USB_METADATA_HANDLER_H_
#define CAMERA_HAL_USB_METADATA_HANDLER_H_
#include <map>
#include <memory>
#include <vector>
#include <base/threading/thread_checker.h>
#include <camera/camera_metadata.h>
#include <hardware/camera3.h>
#include "cros-camera/common_types.h"
#include "cros-camera/face_detector_client_cros_wrapper.h"
#include "hal/usb/common_types.h"
#include "hal/usb/v4l2_camera_device.h"
namespace cros {
using AwbModeToTemperatureMap =
std::map<camera_metadata_enum_android_control_awb_mode, uint32_t>;
struct CameraMetadataDeleter {
inline void operator()(camera_metadata_t* metadata) const {
free_camera_metadata(metadata);
}
};
typedef std::unique_ptr<camera_metadata_t, CameraMetadataDeleter>
ScopedCameraMetadata;
// MetadataHandler is thread-safe. It is used for saving metadata states of
// CameraDevice.
class MetadataHandler {
public:
MetadataHandler(const camera_metadata_t& static_metadata,
const camera_metadata_t& request_template,
const DeviceInfo& device_info,
V4L2CameraDevice* device,
const SupportedFormats& supported_formats);
~MetadataHandler();
static int FillDefaultMetadata(android::CameraMetadata* static_metadata,
android::CameraMetadata* request_metadata);
static int FillMetadataFromSupportedFormats(
const SupportedFormats& supported_formats,
const DeviceInfo& device_info,
android::CameraMetadata* static_metadata,
android::CameraMetadata* request_metadata);
static int FillMetadataFromDeviceInfo(
const DeviceInfo& device_info,
android::CameraMetadata* static_metadata,
android::CameraMetadata* request_metadata);
static int FillSensorInfo(const DeviceInfo& device_info,
android::CameraMetadata* metadata,
int32_t array_width,
int32_t array_height);
// Get default settings according to the |template_type|. Can be called on
// any thread.
const camera_metadata_t* GetDefaultRequestSettings(int template_type);
// PreHandleRequest and PostHandleRequest should run on the same thread.
// Called before the request is processed. This function is used for checking
// metadata values to setup related states and image settings.
int PreHandleRequest(int frame_number,
const Size& resolution,
android::CameraMetadata* metadata);
// Called after the request is processed. This function is used to update
// required metadata which can be gotton from 3A or image processor.
int PostHandleRequest(int frame_number,
int64_t timestamp,
const Size& resolution,
const std::vector<human_sensing::CrosFace>& faces,
android::CameraMetadata* metadata);
private:
// Check |template_type| is valid or not.
bool IsValidTemplateType(int template_type);
// Check if constant frame rate should be enabled or not.
bool ShouldEnableConstantFrameRate(
const android::CameraMetadata* metadata) const;
// Return a copy of metadata according to |template_type|.
ScopedCameraMetadata CreateDefaultRequestSettings(int template_type);
int FillDefaultPreviewSettings(android::CameraMetadata* metadata);
int FillDefaultStillCaptureSettings(android::CameraMetadata* metadata);
int FillDefaultVideoRecordSettings(android::CameraMetadata* metadata);
int FillDefaultVideoSnapshotSettings(android::CameraMetadata* metadata);
int FillDefaultZeroShutterLagSettings(android::CameraMetadata* metadata);
int FillDefaultManualSettings(android::CameraMetadata* metadata);
static AwbModeToTemperatureMap GetAvailableAwbTemperatures(
const DeviceInfo& device_info);
// Metadata containing persistent camera characteristics.
android::CameraMetadata static_metadata_;
// The base template for constructing request settings.
android::CameraMetadata request_template_;
// Static array of standard camera settings templates. These are owned by
// CameraClient.
ScopedCameraMetadata template_settings_[CAMERA3_TEMPLATE_COUNT];
// Use to check PreHandleRequest and PostHandleRequest are called on the same
// thread.
base::ThreadChecker thread_checker_;
// Camera device information.
const DeviceInfo device_info_;
// Delegate to communicate with camera device. Caller owns the ownership.
V4L2CameraDevice* device_;
int current_frame_number_;
bool af_trigger_;
int max_supported_fps_;
// Awb mode to color temperature map
AwbModeToTemperatureMap awb_temperature_;
bool is_awb_control_supported_;
bool is_brightness_control_supported_;
bool is_contrast_control_supported_;
bool is_pan_control_supported_;
bool is_saturation_control_supported_;
bool is_sharpness_control_supported_;
bool is_tilt_control_supported_;
bool is_zoom_control_supported_;
uint32_t focus_distance_normalize_factor_;
ControlRange focus_distance_range_;
};
} // namespace cros
#endif // CAMERA_HAL_USB_METADATA_HANDLER_H_
| 35.513333 | 79 | 0.750704 | [
"vector"
] |
bd128f5ee0599794540253e89d9cabbd817d9098 | 1,928 | h | C | cclient/response/get_tips.h | JakeSCahill/iota.c | a3dfd78c685d8805ccd586f603037d205c26a57d | [
"Apache-2.0"
] | null | null | null | cclient/response/get_tips.h | JakeSCahill/iota.c | a3dfd78c685d8805ccd586f603037d205c26a57d | [
"Apache-2.0"
] | null | null | null | cclient/response/get_tips.h | JakeSCahill/iota.c | a3dfd78c685d8805ccd586f603037d205c26a57d | [
"Apache-2.0"
] | 1 | 2021-09-24T22:18:26.000Z | 2021-09-24T22:18:26.000Z | /*
* Copyright (c) 2018 IOTA Stiftung
* https://github.com/iotaledger/iota.c
*
* Refer to the LICENSE file for licensing information
*/
/**
* @ingroup response
*
* @{
*
* @file
* @brief
*
*/
#ifndef CCLIENT_RESPONSE_GET_TIPS_H
#define CCLIENT_RESPONSE_GET_TIPS_H
#include "common/errors.h"
#include "utils/containers/hash/hash243_stack.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief The data structure of the get tips response.
*
*/
typedef struct get_tips_res_s {
hash243_stack_t hashes; /*!< Current tip transaction hashes */
} get_tips_res_t;
/**
* @brief Allocates a get tips response.
*
* @return A pointer to the response object.
*/
get_tips_res_t* get_tips_res_new();
/**
* @brief Gets the number of tip transactions.
*
* @param[in] res The response object.
* @return Number of tip transactions.
*/
size_t get_tips_res_hash_num(get_tips_res_t* res);
/**
* @brief Frees a get tips response.
*
* @param[in] res The response object.
*/
void get_tips_res_free(get_tips_res_t** res);
/**
* @brief Adds a tip transaction hash to the response.
*
* @param[in] res The response object.
* @param[in] hash A tip transaction hash.
* @return #retcode_t
*/
static inline retcode_t get_tips_res_hashes_push(get_tips_res_t* res, flex_trit_t const* const hash) {
if (!res || !hash) {
return RC_NULL_PARAM;
}
return hash243_stack_push(&res->hashes, hash);
}
/**
* @brief Removes a tip transaction from the response.
*
* @param[in] res The response object.
* @param[in] buf A tip transaction hash.
* @return #retcode_t
*/
static inline retcode_t get_tips_res_hashes_pop(get_tips_res_t* res, flex_trit_t* const buf) {
if (!res || !buf) {
return RC_NULL_PARAM;
}
memcpy(buf, hash243_stack_peek(res->hashes), FLEX_TRIT_SIZE_243);
hash243_stack_pop(&res->hashes);
return RC_OK;
}
#ifdef __cplusplus
}
#endif
#endif // CCLIENT_RESPONSE_GET_TIPS_H
/** @} */
| 20.510638 | 102 | 0.702801 | [
"object"
] |
bd1810c5d036e24471051e1156272eb9bbd85d2e | 3,295 | h | C | third_party/gecko-16/win32/include/nsIIdentityInfo.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | third_party/gecko-16/win32/include/nsIIdentityInfo.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | third_party/gecko-16/win32/include/nsIIdentityInfo.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/security/manager/ssl/public/nsIIdentityInfo.idl
*/
#ifndef __gen_nsIIdentityInfo_h__
#define __gen_nsIIdentityInfo_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIIdentityInfo */
#define NS_IIDENTITYINFO_IID_STR "e9da87b8-b87c-4bd1-a6bc-5a9a2c7f6d8d"
#define NS_IIDENTITYINFO_IID \
{0xe9da87b8, 0xb87c, 0x4bd1, \
{ 0xa6, 0xbc, 0x5a, 0x9a, 0x2c, 0x7f, 0x6d, 0x8d }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIIdentityInfo : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IIDENTITYINFO_IID)
/* readonly attribute boolean isExtendedValidation; */
NS_SCRIPTABLE NS_IMETHOD GetIsExtendedValidation(bool *aIsExtendedValidation) = 0;
/* ACString getValidEVPolicyOid (); */
NS_SCRIPTABLE NS_IMETHOD GetValidEVPolicyOid(nsACString & _retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIIdentityInfo, NS_IIDENTITYINFO_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIIDENTITYINFO \
NS_SCRIPTABLE NS_IMETHOD GetIsExtendedValidation(bool *aIsExtendedValidation); \
NS_SCRIPTABLE NS_IMETHOD GetValidEVPolicyOid(nsACString & _retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIIDENTITYINFO(_to) \
NS_SCRIPTABLE NS_IMETHOD GetIsExtendedValidation(bool *aIsExtendedValidation) { return _to GetIsExtendedValidation(aIsExtendedValidation); } \
NS_SCRIPTABLE NS_IMETHOD GetValidEVPolicyOid(nsACString & _retval NS_OUTPARAM) { return _to GetValidEVPolicyOid(_retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIIDENTITYINFO(_to) \
NS_SCRIPTABLE NS_IMETHOD GetIsExtendedValidation(bool *aIsExtendedValidation) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetIsExtendedValidation(aIsExtendedValidation); } \
NS_SCRIPTABLE NS_IMETHOD GetValidEVPolicyOid(nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetValidEVPolicyOid(_retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsIdentityInfo : public nsIIdentityInfo
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIIDENTITYINFO
nsIdentityInfo();
private:
~nsIdentityInfo();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsIdentityInfo, nsIIdentityInfo)
nsIdentityInfo::nsIdentityInfo()
{
/* member initializers and constructor code */
}
nsIdentityInfo::~nsIdentityInfo()
{
/* destructor code */
}
/* readonly attribute boolean isExtendedValidation; */
NS_IMETHODIMP nsIdentityInfo::GetIsExtendedValidation(bool *aIsExtendedValidation)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* ACString getValidEVPolicyOid (); */
NS_IMETHODIMP nsIdentityInfo::GetValidEVPolicyOid(nsACString & _retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIIdentityInfo_h__ */
| 31.682692 | 176 | 0.791199 | [
"object"
] |
bd1e645b2712e80ba2241f4bfa9ec817e6c63a5e | 5,644 | h | C | aten/src/ATen/cuda/CUDAEvent.h | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | 206 | 2020-11-28T22:56:38.000Z | 2022-03-27T02:33:04.000Z | aten/src/ATen/cuda/CUDAEvent.h | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | 19 | 2020-12-09T23:13:14.000Z | 2022-01-24T23:24:08.000Z | aten/src/ATen/cuda/CUDAEvent.h | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | 28 | 2020-11-29T15:25:12.000Z | 2022-01-20T02:16:27.000Z | #pragma once
#include <ATen/cuda/ATenCUDAGeneral.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAStream.h>
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/Exceptions.h>
#include <c10/util/Exception.h>
#include <cuda_runtime_api.h>
#include <cstdint>
#include <utility>
namespace at { namespace cuda {
/*
* CUDAEvents are movable not copyable wrappers around CUDA's events.
*
* CUDAEvents are constructed lazily when first recorded unless it is
* reconstructed from a cudaIpcEventHandle_t. The event has a device, and this
* device is acquired from the first recording stream. However, if reconstructed
* from a handle, the device should be explicitly specified; or if ipc_handle() is
* called before the event is ever recorded, it will use the current device.
* Later streams that record the event must match this device.
*/
struct TORCH_CUDA_API CUDAEvent {
// Constructors
// Default value for `flags` is specified below - it's cudaEventDisableTiming
CUDAEvent() {}
CUDAEvent(unsigned int flags) : flags_{flags} {}
CUDAEvent(
DeviceIndex device_index, const cudaIpcEventHandle_t* handle) {
#ifndef __HIP_PLATFORM_HCC__
device_index_ = device_index;
CUDAGuard guard(device_index_);
AT_CUDA_CHECK(cudaIpcOpenEventHandle(&event_, *handle));
is_created_ = true;
#else
AT_ERROR("cuIpcOpenEventHandle with HIP is not supported");
#endif
}
// Note: event destruction done on creating device to avoid creating a
// CUDA context on other devices.
~CUDAEvent() {
try {
if (is_created_) {
CUDAGuard guard(device_index_);
cudaEventDestroy(event_);
}
} catch (...) { /* No throw */ }
}
CUDAEvent(const CUDAEvent&) = delete;
CUDAEvent& operator=(const CUDAEvent&) = delete;
CUDAEvent(CUDAEvent&& other) { moveHelper(std::move(other)); }
CUDAEvent& operator=(CUDAEvent&& other) {
moveHelper(std::move(other));
return *this;
}
operator cudaEvent_t() const { return event(); }
// Less than operator (to allow use in sets)
friend bool operator<(const CUDAEvent& left, const CUDAEvent& right) {
return left.event_ < right.event_;
}
optional<at::Device> device() const {
if (is_created_) {
return at::Device(at::kCUDA, device_index_);
} else {
return {};
}
}
bool isCreated() const { return is_created_; }
DeviceIndex device_index() const {return device_index_;}
cudaEvent_t event() const { return event_; }
// Note: cudaEventQuery can be safely called from any device
bool query() const {
if (!is_created_) {
return true;
}
cudaError_t err = cudaEventQuery(event_);
if (err == cudaSuccess) {
return true;
} else if (err != cudaErrorNotReady) {
C10_CUDA_CHECK(err);
}
return false;
}
void record() { record(getCurrentCUDAStream()); }
void recordOnce(const CUDAStream& stream) {
if (!was_recorded_) record(stream);
}
// Note: cudaEventRecord must be called on the same device as the event.
void record(const CUDAStream& stream) {
if (!is_created_) {
createEvent(stream.device_index());
}
TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_,
" does not match recording stream's device ", stream.device_index(), ".");
CUDAGuard guard(device_index_);
AT_CUDA_CHECK(cudaEventRecord(event_, stream));
was_recorded_ = true;
}
// Note: cudaStreamWaitEvent must be called on the same device as the stream.
// The event has no actual GPU resources associated with it.
void block(const CUDAStream& stream) {
if (is_created_) {
CUDAGuard guard(stream.device_index());
AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_, 0));
}
}
// Note: cudaEventElapsedTime can be safely called from any device
float elapsed_time(const CUDAEvent& other) const {
TORCH_CHECK(is_created_ && other.isCreated(),
"Both events must be recorded before calculating elapsed time.");
float time_ms = 0;
// raise cudaErrorNotReady if either event is recorded but not yet completed
AT_CUDA_CHECK(cudaEventElapsedTime(&time_ms, event_, other.event_));
return time_ms;
}
// Note: cudaEventSynchronize can be safely called from any device
void synchronize() const {
if (is_created_) {
AT_CUDA_CHECK(cudaEventSynchronize(event_));
}
}
// Note: cudaIpcGetEventHandle must be called on the same device as the event
void ipc_handle(cudaIpcEventHandle_t * handle) {
#ifndef __HIP_PLATFORM_HCC__
if (!is_created_) {
// this CUDAEvent object was initially constructed from flags but event_
// is not created yet.
createEvent(getCurrentCUDAStream().device_index());
}
CUDAGuard guard(device_index_);
AT_CUDA_CHECK(cudaIpcGetEventHandle(handle, event_));
#else
AT_ERROR("cuIpcGetEventHandle with HIP is not supported");
#endif
}
private:
unsigned int flags_ = cudaEventDisableTiming;
bool is_created_ = false;
bool was_recorded_ = false;
DeviceIndex device_index_ = -1;
cudaEvent_t event_;
void createEvent(DeviceIndex device_index) {
device_index_ = device_index;
CUDAGuard guard(device_index_);
AT_CUDA_CHECK(cudaEventCreateWithFlags(&event_, flags_));
is_created_ = true;
}
void moveHelper(CUDAEvent&& other) {
std::swap(flags_, other.flags_);
std::swap(is_created_, other.is_created_);
std::swap(was_recorded_, other.was_recorded_);
std::swap(device_index_, other.device_index_);
std::swap(event_, other.event_);
}
};
} // namespace cuda
} // namespace at
| 30.344086 | 87 | 0.69915 | [
"object"
] |
bd26d86a34a0942da61f08c040fdd6a0ec47a2cf | 7,436 | h | C | paddle/pten/core/kernel_factory.h | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2022-01-21T07:28:49.000Z | 2022-01-21T07:28:49.000Z | paddle/pten/core/kernel_factory.h | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | null | null | null | paddle/pten/core/kernel_factory.h | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2021-08-21T06:57:20.000Z | 2021-08-21T06:57:20.000Z | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <ostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include "paddle/pten/common/backend.h"
#include "paddle/pten/common/data_type.h"
#include "paddle/pten/common/layout.h"
#include "paddle/pten/core/convert_utils.h"
#include "paddle/pten/core/kernel_def.h"
// See Note [ Why still include the fluid headers? ]
#include "paddle/fluid/platform/enforce.h"
#include "paddle/utils/flat_hash_map.h"
#include "paddle/utils/small_vector.h"
namespace pten {
using DataType = paddle::experimental::DataType;
using DataLayout = paddle::experimental::DataLayout;
/**
* [ Naming considerations ]
*
* The tensor operation library contains many kernels, and the computation
* in each specific scenario is represented by an kernel.
*
* We directly named it `Kernel` instead of `Kernel`, the tensor operation
* library here and fluid are independent, avoiding developers from
* misunderstanding the relationship between the two concepts.
*/
class KernelContext;
using KernelFn = void (*)(KernelContext* ctx);
class KernelKey {
public:
KernelKey() = default;
KernelKey(Backend backend, DataLayout layout, DataType dtype)
: backend_(backend), layout_(layout), dtype_(dtype) {}
Backend backend() const { return backend_; }
DataLayout layout() const { return layout_; }
DataType dtype() const { return dtype_; }
struct Hash {
// Note: Now the number of bits we need does not exceed 32 bits, so there is
// no need to use 64 bits. If needed in the future, it can be expanded,
// but now we don’t over-design.
uint32_t operator()(const KernelKey& key) const;
};
uint32_t hash_value() const { return Hash()(*this); }
bool operator<(const KernelKey& key) const {
return hash_value() < key.hash_value();
}
bool operator==(const KernelKey& key) const {
return hash_value() == key.hash_value();
}
bool operator!=(const KernelKey& key) const {
return hash_value() != key.hash_value();
}
private:
// In total should be smaller than 32.
constexpr static int kBackendBitLength = 8;
constexpr static int kDataLayoutBitLength = 4;
constexpr static int kDataTypeBitLength = 8;
Backend backend_{Backend::UNDEFINED};
DataLayout layout_{DataLayout::UNDEFINED};
DataType dtype_{DataType::UNDEFINED};
};
// TODO(chenweihang): how deal with vector<Param>?
struct TensorArgDef {
Backend backend;
DataLayout layout;
DataType dtype;
TensorArgDef(Backend in_backend, DataLayout in_layout, DataType in_dtype)
: backend(in_backend), layout(in_layout), dtype(in_dtype) {}
TensorArgDef& SetBackend(Backend in_backend) {
backend = in_backend;
return *this;
}
TensorArgDef& SetDataLayout(DataLayout in_layout) {
layout = in_layout;
return *this;
}
TensorArgDef& SetDataType(DataType in_dtype) {
dtype = in_dtype;
return *this;
}
};
struct AttributeArgDef {
std::type_index type_index;
explicit AttributeArgDef(std::type_index type_index)
: type_index(type_index) {}
};
class KernelArgsDef {
public:
KernelArgsDef() = default;
void AppendInput(Backend backend, DataLayout layout, DataType dtype) {
input_defs_.emplace_back(TensorArgDef(backend, layout, dtype));
}
void AppendOutput(Backend backend, DataLayout layout, DataType dtype) {
output_defs_.emplace_back(TensorArgDef(backend, layout, dtype));
}
void AppendAttribute(std::type_index type_index) {
attribute_defs_.emplace_back(AttributeArgDef(type_index));
}
const paddle::SmallVector<TensorArgDef>& input_defs() const {
return input_defs_;
}
const paddle::SmallVector<TensorArgDef>& output_defs() const {
return output_defs_;
}
const paddle::SmallVector<AttributeArgDef>& attribute_defs() const {
return attribute_defs_;
}
paddle::SmallVector<TensorArgDef>& input_defs() { return input_defs_; }
paddle::SmallVector<TensorArgDef>& output_defs() { return output_defs_; }
paddle::SmallVector<AttributeArgDef>& attribute_defs() {
return attribute_defs_;
}
private:
paddle::SmallVector<TensorArgDef> input_defs_{{}};
paddle::SmallVector<TensorArgDef> output_defs_{{}};
paddle::SmallVector<AttributeArgDef> attribute_defs_{{}};
};
class Kernel {
public:
// for map element contruct
Kernel() = default;
explicit Kernel(KernelFn fn, void* variadic_fn)
: fn_(fn), variadic_fn_(variadic_fn) {}
void operator()(KernelContext* ctx) const { fn_(ctx); }
template <typename Fn>
Fn GetVariadicKernelFn() const {
auto* func = reinterpret_cast<Fn>(variadic_fn_);
return func;
}
KernelArgsDef* mutable_args_def() { return &args_def_; }
const KernelArgsDef& args_def() const { return args_def_; }
TensorArgDef& InputAt(size_t idx) { return args_def_.input_defs().at(idx); }
TensorArgDef& OutputAt(size_t idx) { return args_def_.output_defs().at(idx); }
bool IsValid() { return fn_ != nullptr; }
private:
KernelFn fn_{nullptr};
void* variadic_fn_ = nullptr;
KernelArgsDef args_def_;
};
/**
* Note: Each Computation need a basic kernel map that named by kernel_name.
* Such as for scale op, KernelMap contains a `scale` kernel map,
* if it still need other overload kernel, the op name can be
* `scale.***`.
*/
class KernelFactory {
public:
// replaced by paddle::flat_hash_map later
using KernelMap = paddle::flat_hash_map<
std::string,
paddle::flat_hash_map<KernelKey, Kernel, KernelKey::Hash>>;
static KernelFactory& Instance();
KernelMap& kernels() { return kernels_; }
bool HasCompatiblePtenKernel(const std::string& op_type) const {
return kernels_.find(TransToPtenKernelName(op_type)) != kernels_.end();
}
const Kernel& SelectKernelOrThrowError(const std::string& kernel_name,
const KernelKey& kernel_key) const;
const Kernel& SelectKernelOrThrowError(const std::string& kernel_name,
Backend backend,
DataLayout layout,
DataType dtype) const;
Kernel SelectKernel(const std::string& kernel_name,
const KernelKey& kernel_key) const;
paddle::flat_hash_map<KernelKey, Kernel, KernelKey::Hash> SelectKernelMap(
const std::string& kernel_name) const;
private:
KernelFactory() = default;
KernelMap kernels_;
};
inline std::ostream& operator<<(std::ostream& os, const KernelKey& kernel_key) {
os << "(" << kernel_key.backend() << ", " << kernel_key.layout() << ", "
<< kernel_key.dtype() << ")";
return os;
}
std::ostream& operator<<(std::ostream& os, const Kernel& kernel);
std::ostream& operator<<(std::ostream& os, KernelFactory& kernel_factory);
} // namespace pten
| 29.160784 | 80 | 0.703201 | [
"vector"
] |
bd2794787f95541bdcf57a6807725d4ec70d60e9 | 22,915 | h | C | third_party/libSBML-5.9.0-Source/src/sbml/Constraint.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | third_party/libSBML-5.9.0-Source/src/sbml/Constraint.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | third_party/libSBML-5.9.0-Source/src/sbml/Constraint.h | 0u812/roadrunner | f464c2649e388fa1f5a015592b0b29b65cc84b4b | [
"Apache-2.0"
] | null | null | null | /**
* @file Constraint.h
* @brief Definitions of Constraint and ListOfConstraints.
* @author Ben Bornstein
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EBML-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*
* @class Constraint
* @sbmlbrief{core} Implementation of SBML's %Constraint construct.
*
* The Constraint object class was introduced in SBML Level 2
* Version 2 as a mechanism for stating the assumptions under which a
* model is designed to operate. The <em>constraints</em> are statements
* about permissible values of different quantities in a model.
* Constraints are not used to compute dynamical values for simulation or
* analysis, but rather, they serve an advisory role for
* simulation/analysis tools.
*
* SBML's Constraint object class has one required attribute, "id", to
* give the parameter a unique identifier by which other parts of an SBML
* model definition can refer to it. A Constraint object can also have an
* optional "name" attribute of type @c string. Identifiers and names must
* be used according to the guidelines described in the SBML specification
* (e.g., Section 3.3 in the Level 2 Version 4 specification).
*
* Constraint has one required subelement, "math", containing a MathML
* formula defining the condition of the constraint. This formula must
* return a boolean value of @c true when the model is a <em>valid</em>
* state. The formula can be an arbitrary expression referencing the
* variables and other entities in an SBML model. The evaluation of "math"
* and behavior of constraints are described in more detail below.
*
* A Constraint structure also has an optional subelement called "message".
* This can contain a message in XHTML format that may be displayed to the
* user when the condition of the formula in the "math" subelement
* evaluates to a value of @c false. Software tools are not required to
* display the message, but it is recommended that they do so as a matter
* of best practice. The XHTML content within a "message" subelement must
* follow the same restrictions as for the "notes" element on SBase
* described in in the SBML Level 2 specification; please consult the
* <a target="_blank" href="http://sbml.org/Documents/Specifications">SBML
* specification document</a> corresponding to the SBML Level and Version
* of your model for more information about the requirements for "notes"
* content.
*
* Constraint was introduced in SBML Level 2 Version 2. It is
* not available in earlier versions of Level 2 nor in any version of
* Level 1.
*
* @section constraint-semantics Semantics of Constraints
*
* In the context of a simulation, a Constraint has effect at all times
* <em>t \f$\geq\f$ 0</em>. Each Constraint's "math" subelement is first
* evaluated after any InitialAssignment definitions in a model at <em>t =
* 0</em> and can conceivably trigger at that point. (In other words, a
* simulation could fail a constraint immediately.)
*
* Constraint structures <em>cannot and should not</em> be used to compute
* the dynamical behavior of a model as part of, for example, simulation.
* Constraints may be used as input to non-dynamical analysis, for instance
* by expressing flux constraints for flux balance analysis.
*
* The results of a simulation of a model containing a constraint are
* invalid from any simulation time at and after a point when the function
* given by the "math" subelement returns a value of @c false. Invalid
* simulation results do not make a prediction of the behavior of the
* biochemical reaction network represented by the model. The precise
* behavior of simulation tools is left undefined with respect to
* constraints. If invalid results are detected with respect to a given
* constraint, the "message" subelement may optionally be displayed to the
* user. The simulation tool may also halt the simulation or clearly
* delimit in output data the simulation time point at which the simulation
* results become invalid.
*
* SBML does not impose restrictions on duplicate Constraint definitions or
* the order of evaluation of Constraint objects in a model. It is
* possible for a model to define multiple constraints all with the same
* mathematical expression. Since the failure of any constraint indicates
* that the model simulation has entered an invalid state, a system is not
* required to attempt to detect whether other constraints in the model
* have failed once any one constraint has failed.
*
* <!---------------------------------------------------------------------- -->
*
* @class ListOfConstraints
* @sbmlbrief{core} Implementation of SBML's %ListOfConstraints construct.
*
* @copydetails doc_what_is_listof
*/
/**
* <!-- ~ ~ ~ ~ ~ Start of common documentation strings ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
* The following text is used as common documentation blocks copied multiple
* times elsewhere in this file. The use of @class is a hack needed because
* Doxygen's @copydetails command has limited functionality. Symbols
* beginning with "doc_" are marked as ignored in our Doxygen configuration.
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ -->
*
* @class doc_constraint_setting_lv
*
* @note Upon the addition of a Constraint object to an SBMLDocument
* (e.g., using Model::addConstraint(@if java Constraint c@endif)), the
* SBML Level, SBML Version and XML namespace of the document @em
* override the values used when creating the Constraint object via this
* constructor. This is necessary to ensure that an SBML document is a
* consistent structure. Nevertheless, the ability to supply the values
* at the time of creation of a Constraint is an important aid to
* producing valid SBML. Knowledge of the intented SBML Level and
* Version determine whether it is valid to assign a particular value to
* an attribute, or whether it is valid to add an object to an existing
* SBMLDocument.
*
*/
#ifndef Constraint_h
#define Constraint_h
#include <sbml/common/extern.h>
#include <sbml/common/sbmlfwd.h>
#ifdef __cplusplus
#include <string>
#include <sbml/SBase.h>
#include <sbml/ListOf.h>
LIBSBML_CPP_NAMESPACE_BEGIN
class ASTNode;
class XMLNode;
class SBMLVisitor;
class LIBSBML_EXTERN Constraint : public SBase
{
public:
/**
* Creates a new Constraint using the given SBML @p level and @p version
* values.
*
* @param level an unsigned int, the SBML Level to assign to this Constraint
*
* @param version an unsigned int, the SBML Version to assign to this
* Constraint
*
* @throws @if python ValueError @else SBMLConstructorException @endif@~
* Thrown if the given @p level and @p version combination, or this kind
* of SBML object, are either invalid or mismatched with respect to the
* parent SBMLDocument object.
*
* @copydetails doc_constraint_setting_lv
*/
Constraint (unsigned int level, unsigned int version);
/**
* Creates a new Constraint using the given SBMLNamespaces object
* @p sbmlns.
*
* @copydetails doc_what_are_sbmlnamespaces
*
* @param sbmlns an SBMLNamespaces object.
*
* @throws @if python ValueError @else SBMLConstructorException @endif@~
* Thrown if the given @p level and @p version combination, or this kind
* of SBML object, are either invalid or mismatched with respect to the
* parent SBMLDocument object.
*
* @copydetails doc_constraint_setting_lv
*/
Constraint (SBMLNamespaces* sbmlns);
/**
* Destroys this Constraint.
*/
virtual ~Constraint ();
/**
* Copy constructor; creates a copy of this Constraint.
*
* @param orig the object to copy.
*
* @throws @if python ValueError @else SBMLConstructorException @endif@~
* Thrown if the argument @p orig is @c NULL.
*/
Constraint (const Constraint& orig);
/**
* Assignment operator for Constraint.
*
* @param rhs The object whose values are used as the basis of the
* assignment.
*
* @throws @if python ValueError @else SBMLConstructorException @endif@~
* Thrown if the argument @p rhs is @c NULL.
*/
Constraint& operator=(const Constraint& rhs);
/**
* Accepts the given SBMLVisitor for this instance of Constraint.
*
* @param v the SBMLVisitor instance to be used.
*
* @return the result of calling <code>v.visit()</code>, which indicates
* whether the Visitor would like to visit the next Constraint in the
* list of constraints within which this Constraint is embedded (i.e., in
* the ListOfConstraints located in the enclosing Model instance).
*/
virtual bool accept (SBMLVisitor& v) const;
/**
* Creates and returns a deep copy of this Constraint.
*
* @return a (deep) copy of this Constraint.
*/
virtual Constraint* clone () const;
/**
* Get the message, if any, associated with this Constraint
*
* @return the message for this Constraint, as an XMLNode.
*/
const XMLNode* getMessage () const;
/**
* Get the message string, if any, associated with this Constraint
*
* @return the message for this Constraint, as a string.
*/
std::string getMessageString () const;
/**
* Get the mathematical expression of this Constraint
*
* @return the math for this Constraint, as an ASTNode.
*/
const ASTNode* getMath () const;
/**
* Predicate returning @c true if a
* message is defined for this Constraint.
*
* @return @c true if the message of this Constraint is set,
* @c false otherwise.
*/
bool isSetMessage () const;
/**
* Predicate returning @c true if a
* mathematical formula is defined for this Constraint.
*
* @return @c true if the "math" subelement for this Constraint is
* set, @c false otherwise.
*/
bool isSetMath () const;
/**
* Sets the message of this Constraint.
*
* The XMLNode tree passed in @p xhtml is copied.
*
* @param xhtml an XML tree containing XHTML content.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif@~ The possible values
* returned by this function are:
* @li @link OperationReturnValues_t#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link OperationReturnValues_t#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
*/
int setMessage (const XMLNode* xhtml);
/**
* Sets the mathematical expression of this Constraint to a copy of the
* AST given as @p math.
*
* @param math an ASTNode expression to be assigned as the "math"
* subelement of this Constraint
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif@~ The possible values
* returned by this function are:
* @li @link OperationReturnValues_t#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link OperationReturnValues_t#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink
*/
int setMath (const ASTNode* math);
/**
* Unsets the "message" subelement of this Constraint.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif@~ The possible values
* returned by this function are:
* @li @link OperationReturnValues_t#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link OperationReturnValues_t#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED @endlink
*/
int unsetMessage ();
/**
* Renames all the @c SIdRef attributes on this element, including any
* found in MathML.
*
* @copydetails doc_what_is_sidref
*
* This method works by looking at all attributes and (if appropriate)
* mathematical formulas, comparing the identifiers to the value of @p
* oldid. If any matches are found, the matching identifiers are replaced
* with @p newid. The method does @em not descend into child elements.
*
* @param oldid the old identifier
* @param newid the new identifier
*/
virtual void renameSIdRefs(const std::string& oldid, const std::string& newid);
/**
* Renames all the @c UnitSIdRef attributes on this element.
*
* @copydetails doc_what_is_unitsidref
*
* This method works by looking at all unit identifier attribute values
* (including, if appropriate, inside mathematical formulas), comparing the
* unit identifiers to the value of @p oldid. If any matches are found,
* the matching identifiers are replaced with @p newid. The method does
* @em not descend into child elements.
*
* @param oldid the old identifier
* @param newid the new identifier
*/
virtual void renameUnitSIdRefs(const std::string& oldid, const std::string& newid);
/** @cond doxygenLibsbmlInternal */
/**
* Replace all nodes with the name 'id' from the child 'math' object with the provided function.
*
*/
virtual void replaceSIDWithFunction(const std::string& id, const ASTNode* function);
/** @endcond */
/**
* Returns the libSBML type code for this SBML object.
*
* @copydetails doc_what_are_typecodes
*
* @return the SBML type code for this object:
* @link SBMLTypeCode_t#SBML_CONSTRAINT SBML_CONSTRAINT@endlink (default).
*
* @copydetails doc_warning_typecodes_not_unique
*
* @see getElementName()
* @see getPackageName()
*/
virtual int getTypeCode () const;
/**
* Returns the XML element name of this object, which for Constraint, is
* always @c "constraint".
*
* @return the name of this element, i.e., @c "constraint".
*/
virtual const std::string& getElementName () const;
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to write out their contained
* SBML objects as XML elements. Be sure to call your parents
* implementation of this method as well.
*/
virtual void writeElements (XMLOutputStream& stream) const;
/** @endcond */
/**
* Predicate returning @c true if
* all the required elements for this Constraint object
* have been set.
*
* @note The required elements for a Constraint object are:
* @li 'math'
*
* @return a boolean value indicating whether all the required
* elements for this object have been defined.
*/
virtual bool hasRequiredElements() const;
protected:
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to read (and store) XHTML,
* MathML, etc. directly from the XMLInputStream.
*
* @return true if the subclass read from the stream, false otherwise.
*/
virtual bool readOtherXML (XMLInputStream& stream);
/**
* Subclasses should override this method to get the list of
* expected attributes.
* This function is invoked from corresponding readAttributes()
* function.
*/
virtual void addExpectedAttributes(ExpectedAttributes& attributes);
/**
* Subclasses should override this method to read values from the given
* XMLAttributes set into their specific fields. Be sure to call your
* parents implementation of this method as well.
*/
virtual void readAttributes (const XMLAttributes& attributes,
const ExpectedAttributes& expectedAttributes);
void readL2Attributes (const XMLAttributes& attributes);
void readL3Attributes (const XMLAttributes& attributes);
/**
* Subclasses should override this method to write their XML attributes
* to the XMLOutputStream. Be sure to call your parents implementation
* of this method as well.
*/
virtual void writeAttributes (XMLOutputStream& stream) const;
ASTNode* mMath;
XMLNode* mMessage;
/* the validator classes need to be friends to access the
* protected constructor that takes no arguments
*/
friend class Validator;
friend class ConsistencyValidator;
friend class IdentifierConsistencyValidator;
friend class InternalConsistencyValidator;
friend class L1CompatibilityValidator;
friend class L2v1CompatibilityValidator;
friend class L2v2CompatibilityValidator;
friend class L2v3CompatibilityValidator;
friend class L2v4CompatibilityValidator;
friend class MathMLConsistencyValidator;
friend class ModelingPracticeValidator;
friend class OverdeterminedValidator;
friend class SBOConsistencyValidator;
friend class UnitConsistencyValidator;
/** @endcond */
};
class LIBSBML_EXTERN ListOfConstraints : public ListOf
{
public:
/**
* Creates a new ListOfConstraints object.
*
* The object is constructed such that it is valid for the given SBML
* Level and Version combination.
*
* @param level the SBML Level
*
* @param version the Version within the SBML Level
*/
ListOfConstraints (unsigned int level, unsigned int version);
/**
* Creates a new ListOfConstraints object.
*
* The object is constructed such that it is valid for the SBML Level and
* Version combination determined by the SBMLNamespaces object in @p
* sbmlns.
*
* @param sbmlns an SBMLNamespaces object that is used to determine the
* characteristics of the ListOfConstraints object to be created.
*/
ListOfConstraints (SBMLNamespaces* sbmlns);
/**
* Creates and returns a deep copy of this ListOfConstraints instance.
*
* @return a (deep) copy of this ListOfConstraints.
*/
virtual ListOfConstraints* clone () const;
/**
* Returns the libSBML type code for the objects contained in this ListOf
* (i.e., Constraint objects, if the list is non-empty).
*
* @copydetails doc_what_are_typecodes
*
* @return the SBML type code for the objects contained in this ListOf
* instance: @link SBMLTypeCode_t#SBML_CONSTRAINT SBML_CONSTRAINT@endlink (default).
*
* @see getElementName()
* @see getPackageName()
*/
virtual int getItemTypeCode () const;
/**
* Returns the XML element name of this object.
*
* For ListOfConstraints, the XML element name is @c "listOfConstraints".
*
* @return the name of this element, i.e., @c "listOfConstraints".
*/
virtual const std::string& getElementName () const;
/**
* Get a Constraint from the ListOfConstraints.
*
* @param n the index number of the Constraint to get.
*
* @return the nth Constraint in this ListOfConstraints.
*
* @see size()
*/
virtual Constraint * get(unsigned int n);
/**
* Get a Constraint from the ListOfConstraints.
*
* @param n the index number of the Constraint to get.
*
* @return the nth Constraint in this ListOfConstraints.
*
* @see size()
*/
virtual const Constraint * get(unsigned int n) const;
/**
* Removes the nth item from this ListOfConstraints items and returns a
* pointer to it.
*
* The caller owns the returned item and is responsible for deleting it.
*
* @param n the index of the item to remove
*
* @see size()
*/
virtual Constraint* remove (unsigned int n);
/** @cond doxygenLibsbmlInternal */
/**
* Get the ordinal position of this element in the containing object
* (which in this case is the Model object).
*
* The ordering of elements in the XML form of SBML is generally fixed
* for most components in SBML. So, for example, the ListOfConstraints
* in a model is (in SBML Level 2 Version 4) the tenth ListOf___.
* (However, it differs for different Levels and Versions of SBML.)
*
* @return the ordinal position of the element with respect to its
* siblings, or @c -1 (default) to indicate the position is not significant.
*/
virtual int getElementPosition () const;
/** @endcond */
protected:
/** @cond doxygenLibsbmlInternal */
/**
* Create and return an SBML object of this class, if present.
*
* @return the SBML object corresponding to next XMLToken in the
* XMLInputStream or @c NULL if the token was not recognized.
*/
virtual SBase* createObject (XMLInputStream& stream);
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#ifndef SWIG
LIBSBML_CPP_NAMESPACE_BEGIN
BEGIN_C_DECLS
/* ----------------------------------------------------------------------------
* See the .cpp file for the documentation of the following functions.
* --------------------------------------------------------------------------*/
/*
LIBSBML_EXTERN
Constraint_t *
Constraint_createWithLevelVersionAndNamespaces (unsigned int level,
unsigned int version, XMLNamespaces_t *xmlns);
*/
LIBSBML_EXTERN
Constraint_t *
Constraint_create (unsigned int level, unsigned int version);
LIBSBML_EXTERN
Constraint_t *
Constraint_createWithNS (SBMLNamespaces_t *sbmlns);
LIBSBML_EXTERN
void
Constraint_free (Constraint_t *c);
LIBSBML_EXTERN
Constraint_t *
Constraint_clone (const Constraint_t *c);
LIBSBML_EXTERN
const XMLNamespaces_t *
Constraint_getNamespaces(Constraint_t *c);
LIBSBML_EXTERN
const XMLNode_t *
Constraint_getMessage (const Constraint_t *c);
LIBSBML_EXTERN
char*
Constraint_getMessageString (const Constraint_t *c);
LIBSBML_EXTERN
const ASTNode_t *
Constraint_getMath (const Constraint_t *c);
LIBSBML_EXTERN
int
Constraint_isSetMessage (const Constraint_t *c);
LIBSBML_EXTERN
int
Constraint_isSetMath (const Constraint_t *c);
LIBSBML_EXTERN
int
Constraint_setMessage (Constraint_t *c, const XMLNode_t* xhtml);
LIBSBML_EXTERN
int
Constraint_setMath (Constraint_t *c, const ASTNode_t *math);
LIBSBML_EXTERN
int
Constraint_unsetMessage (Constraint_t *c);
END_C_DECLS
LIBSBML_CPP_NAMESPACE_END
#endif /* !SWIG */
#endif /* Constraint_h */
| 31.606897 | 99 | 0.707091 | [
"object",
"model"
] |
bd27a7ee2c6e4be750711333a944fb4f3834aa8f | 3,110 | h | C | Engine/foundation/io/filestream.h | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 26 | 2015-01-15T12:57:40.000Z | 2022-02-16T10:07:12.000Z | Engine/foundation/io/filestream.h | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | null | null | null | Engine/foundation/io/filestream.h | BikkyS/DreamEngine | 47da4e22c65188c72f44591f6a96505d8ba5f5f3 | [
"MIT"
] | 17 | 2015-02-18T07:51:31.000Z | 2020-06-01T01:10:12.000Z | /****************************************************************************
Copyright (c) 2006, Radon Labs GmbH
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
//------------------------------------------------------------------------------
/**
@class IO::FileStream
A stream to which offers read/write access to filesystem files.
*/
#include "io/stream.h"
#include "util/string.h"
#include "io/filetime.h"
#include "io/fswrapper.h"
//------------------------------------------------------------------------------
namespace IO
{
class FileStream : public Stream
{
__DeclareClass(FileStream);
public:
/// constructor
FileStream();
/// destructor
virtual ~FileStream();
/// supports reading?
virtual bool CanRead() const;
/// supports writing?
virtual bool CanWrite() const;
/// supports seeking?
virtual bool CanSeek() const;
/// supports memory mapping (read-only)?
virtual bool CanBeMapped() const;
/// get the size of the stream in bytes
virtual Size GetSize() const;
/// get the current position of the read/write cursor
virtual Position GetPosition() const;
/// open the stream
virtual bool Open();
/// close the stream
virtual void Close();
/// directly write to the stream
virtual void Write(const void* ptr, Size numBytes);
/// directly read from the stream
virtual Size Read(void* ptr, Size numBytes);
/// seek in stream
virtual void Seek(Offset offset, SeekOrigin origin);
/// flush unsaved data
virtual void Flush();
/// return true if end-of-stream reached
virtual bool Eof() const;
/// map stream to memory
virtual void* Map();
/// unmap stream
virtual void Unmap();
virtual bool IsHeader( void* headPtr, Size numBytes ) ;
private:
FSWrapper::Handle handle;
void* mappedContent;
};
} // namespace IO
//------------------------------------------------------------------------------
| 35.747126 | 80 | 0.627331 | [
"3d"
] |
bd2d8ffa1825e275b3f72ae20955129eba67fcd7 | 5,348 | h | C | src/base_level/collision/pfx_mesh_common.h | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | 5 | 2017-10-08T16:06:35.000Z | 2020-10-08T23:30:34.000Z | src/base_level/collision/pfx_mesh_common.h | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | null | null | null | src/base_level/collision/pfx_mesh_common.h | erwincoumans/test2 | cb78f36ae4002d79f21d21c759d07e2e23aabf15 | [
"BSD-3-Clause"
] | null | null | null | /*
Physics Effects Copyright(C) 2010 Sony Computer Entertainment Inc.
All rights reserved.
Physics Effects is open software; you can redistribute it and/or
modify it under the terms of the BSD License.
Physics Effects is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the BSD License for more details.
A copy of the BSD License is distributed with
Physics Effects under the filename: physics_effects_license.txt
*/
#ifndef _SCE_PFX_MESH_COMMON_H
#define _SCE_PFX_MESH_COMMON_H
#include "../../../include/physics_effects/base_level/base/pfx_common.h"
#include "../../../include/physics_effects/base_level/collision/pfx_tri_mesh.h"
namespace sce {
namespace PhysicsEffects {
struct PfxClosestPoints {
PfxPoint3 pA[4],pB[4];
PfxFloat distSqr[4];
PfxFloat closestDistSqr;
int numPoints;
SCE_PFX_PADDING(1,8)
PfxClosestPoints()
{
numPoints = 0;
closestDistSqr = SCE_PFX_FLT_MAX;
}
void set(int i,const PfxPoint3 &pointA,const PfxPoint3 &pointB,PfxFloat d)
{
pA[i] = pointA;
pB[i] = pointB;
distSqr[i] = d;
}
void add(const PfxPoint3 &pointA,const PfxPoint3 &pointB,PfxFloat d)
{
const PfxFloat epsilon = 0.00001f;
if(closestDistSqr < d) return;
closestDistSqr = d + epsilon;
int replaceId = -1;
PfxFloat distMax = -SCE_PFX_FLT_MAX;
for(int i=0;i<numPoints;i++) {
if(lengthSqr(pA[i]-pointA) < epsilon) {
return;
}
if(distMax < distSqr[i]) {
distMax = distSqr[i];
replaceId = i;
}
}
replaceId = (numPoints<4)?(numPoints++):replaceId;
set(replaceId,pointA,pointB,d);
}
};
static SCE_PFX_FORCE_INLINE
PfxUInt32 pfxGatherFacets(
const PfxTriMesh *mesh,
const PfxFloat *aabbHalf,
const PfxVector3 &offsetPos,
const PfxMatrix3 &offsetRot,
PfxUInt8 *selFacets)
{
PfxMatrix3 absOffsetRot = absPerElem(offsetRot);
PfxUInt32 numSelFacets = 0;
for(int f=0;f<(int)mesh->m_numFacets;f++) {
const PfxFacet &facet = mesh->m_facets[f];
PfxVector3 facetCenter = absPerElem(offsetPos + offsetRot * pfxReadVector3(facet.m_center));
PfxVector3 halfBA = absOffsetRot * pfxReadVector3(facet.m_half);
// ConvexBのAABBとチェック
if(facetCenter[0] > (halfBA[0]+aabbHalf[0])) continue;
if(facetCenter[1] > (halfBA[1]+aabbHalf[1])) continue;
if(facetCenter[2] > (halfBA[2]+aabbHalf[2])) continue;
// この面は判定
selFacets[numSelFacets++] = (PfxUInt8)f;
}
return numSelFacets;
}
static SCE_PFX_FORCE_INLINE
void pfxGetProjAxisPnts6(
const PfxVector3 *verts,const PfxVector3 &axis,
PfxFloat &distMin,PfxFloat &distMax)
{
PfxFloat p0 = dot(axis, verts[0]);
PfxFloat p1 = dot(axis, verts[1]);
PfxFloat p2 = dot(axis, verts[2]);
PfxFloat p3 = dot(axis, verts[3]);
PfxFloat p4 = dot(axis, verts[4]);
PfxFloat p5 = dot(axis, verts[5]);
distMin = SCE_PFX_MIN(p5,SCE_PFX_MIN(p4,SCE_PFX_MIN(p3,SCE_PFX_MIN(p2,SCE_PFX_MIN(p0,p1)))));
distMax = SCE_PFX_MAX(p5,SCE_PFX_MAX(p4,SCE_PFX_MAX(p3,SCE_PFX_MAX(p2,SCE_PFX_MAX(p0,p1)))));
}
static SCE_PFX_FORCE_INLINE
void pfxGetProjAxisPnts3(
const PfxVector3 *verts,const PfxVector3 &axis,
PfxFloat &distMin,PfxFloat &distMax)
{
PfxFloat p0 = dot(axis, verts[0]);
PfxFloat p1 = dot(axis, verts[1]);
PfxFloat p2 = dot(axis, verts[2]);
distMin = SCE_PFX_MIN(p2,SCE_PFX_MIN(p0,p1));
distMax = SCE_PFX_MAX(p2,SCE_PFX_MAX(p0,p1));
}
static SCE_PFX_FORCE_INLINE
void pfxGetProjAxisPnts2(
const PfxVector3 *verts,const PfxVector3 &axis,
PfxFloat &distMin,PfxFloat &distMax)
{
PfxFloat p0 = dot(axis, verts[0]);
PfxFloat p1 = dot(axis, verts[1]);
distMin = SCE_PFX_MIN(p0,p1);
distMax = SCE_PFX_MAX(p0,p1);
}
///////////////////////////////////////////////////////////////////////////////
// 2つのベクトルの向きをチェック
static SCE_PFX_FORCE_INLINE
bool pfxIsSameDirection(const PfxVector3 &vecA,const PfxVector3 &vecB)
{
return fabsf(dot(vecA,vecB)) > 0.9999f;
}
///////////////////////////////////////////////////////////////////////////////
// 面ローカルの座標を算出
static SCE_PFX_FORCE_INLINE
void pfxGetLocalCoords(
const PfxVector3 &pointOnTriangle,
const PfxTriangle &triangle,
PfxFloat &s,PfxFloat &t)
{
PfxVector3 v0 = triangle.points[1] - triangle.points[0];
PfxVector3 v1 = triangle.points[2] - triangle.points[0];
PfxVector3 dir = pointOnTriangle - triangle.points[0];
PfxVector3 v = cross( v0, v1 );
PfxVector3 crS = cross( v, v0 );
PfxVector3 crT = cross( v, v1 );
s = dot( crT, dir ) / dot( crT, v0 );
t = dot( crS, dir ) / dot( crS, v1 );
}
// a,bからなる直線上に点pがあるかどうかを判定
static SCE_PFX_FORCE_INLINE
bool pfxPointOnLine(const PfxVector3 &p,const PfxVector3 &a,const PfxVector3 &b)
{
PfxVector3 ab = normalize(b-a);
PfxVector3 q = a + ab * dot(p-a,ab);
return lengthSqr(p-q) < 0.00001f;
}
// 線分a,b上に点pがあるかどうかを判定
static SCE_PFX_FORCE_INLINE
bool pfxPointOnSegment(const PfxVector3 &p,const PfxVector3 &a,const PfxVector3 &b)
{
PfxVector3 ab = b-a;
PfxVector3 ap = p-a;
PfxFloat denom = dot(ab,ab);
PfxFloat num = dot(ap,ab);
PfxFloat t = num/denom;
if(t < 0.0f || t > 1.0f) return false;
return (dot(ap,ap)-num*t) < 0.00001f;
}
} //namespace PhysicsEffects
} //namespace sce
#endif // _SCE_PFX_MESH_COMMON_H
| 27.425641 | 94 | 0.681376 | [
"mesh"
] |
bd337a3b29dc7e371895c4109ff1f5b42ad385c1 | 4,300 | h | C | FEBioFluid/FEBiphasicFSI.h | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | FEBioFluid/FEBiphasicFSI.h | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | FEBioFluid/FEBiphasicFSI.h | wzaylor/FEBio | 5444c06473dd66dc0bfdf6e3b2c79d3c0cd0b7a6 | [
"MIT"
] | null | null | null | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <FEBioMech/FEElasticMaterial.h>
#include "FEFluidFSI.h"
#include <FEBioMix/FEHydraulicPermeability.h>
#include <FEBioMech/FEBodyForce.h>
//-----------------------------------------------------------------------------
//! FSI material point class.
//
class FEBIOFLUID_API FEBiphasicFSIMaterialPoint : public FEMaterialPoint
{
public:
//! constructor
FEBiphasicFSIMaterialPoint(FEMaterialPoint* pt);
//! create a shallow copy
FEMaterialPoint* Copy();
//! data serialization
void Serialize(DumpStream& ar);
//! Data initialization
void Init();
public:
// Biphasic FSI material data
mat3d m_Lw; //!< grad of m_wt
vec3d m_gradJ; //!< gradient of J
double m_phi0; //!< solid volume fraction in reference configuration
mat3ds m_ss; //!< solid stress
};
//-----------------------------------------------------------------------------
//! Base class for FluidFSI materials.
class FEBIOFLUID_API FEBiphasicFSI : public FEFluidFSI
{
public:
FEBiphasicFSI(FEModel* pfem);
// returns a pointer to a new material point object
FEMaterialPoint* CreateMaterialPointData() override;
//! performs initialization
bool Init() override;
public:
//! calculate inner stress at material point
mat3ds Stress(FEMaterialPoint& pt);
//! calculate inner tangent stiffness at material point
tens4ds Tangent(FEMaterialPoint& pt);
//! return the permeability tensor as a matrix
void Permeability(double k[3][3], FEMaterialPoint& pt);
//! return the permeability as a tensor
mat3ds Permeability(FEMaterialPoint& pt);
//! return the inverse permeability as a tensor
mat3ds InvPermeability(FEMaterialPoint& pt);
//! return the tangent permeability tensor
tens4dmm Permeability_Tangent(FEMaterialPoint& pt);
//! return the permeability property
FEHydraulicPermeability* GetPermeability() { return m_pPerm; }
//! porosity
double Porosity(FEMaterialPoint& pt);
//! Solid Volume
double SolidVolumeFrac(FEMaterialPoint& pt);
//! porosity gradient
vec3d gradPorosity(FEMaterialPoint& pt);
//! solid density
double TrueSolidDensity(FEMaterialPoint& mp) { return Solid()->Density(mp); }
//! true fluid density
double TrueFluidDensity(FEMaterialPoint& mp) { return Fluid()->Density(mp); }
//! solid density
double SolidDensity(FEMaterialPoint& mp);
//! fluid density
double FluidDensity(FEMaterialPoint& mp);
public: // material parameters
double m_rhoTw; //!< true fluid density
double m_phi0; //!< solid volume fraction in reference configuration
vector<FEBodyForce*> m_bf; //!< body forces acting on this biphasic material
private: // material properties
FEHydraulicPermeability* m_pPerm; //!< pointer to permeability material
DECLARE_FECORE_CLASS();
};
| 33.858268 | 89 | 0.686279 | [
"object",
"vector",
"solid"
] |
bd452ac3e608da85acb95bfeb255f5222c129c2e | 129,514 | h | C | WRK-V1.2/clr/src/inc/corinfo.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/clr/src/inc/corinfo.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | WRK-V1.2/clr/src/inc/corinfo.h | intj-t/openvmsft | 0d17fbce8607ab2b880be976c2e86d8cfc3e83bb | [
"Intel"
] | null | null | null | // ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/*****************************************************************************\
* *
* CorInfo.h - EE / Code generator interface *
* *
* Version 1.0 *
*******************************************************************************
* *
*
*
* *
*******************************************************************************
*
* This file exposes CLR runtime functionality. It can be used by compilers,
* both Just-in-time and ahead-of-time, to generate native code which
* executes in the runtime environment.
*******************************************************************************
*******************************************************************************
The semantic contract between the EE and the JIT should be documented here
It is incomplete, but as time goes on, that hopefully will change
-------------------------------------------------------------------------------
Class Construction
First of all class contruction comes in two flavors precise and 'beforeFieldInit'.
In C# you get the former if you declare an explicit class constructor method and
the later if you declaratively initialize static fields. Precise class construction
guarentees that the .cctor is run precisely before the first access to any method
or field of the class. 'beforeFieldInit' semantics guarentees only that the
.cctor will be run some time before the first static field access (note that
calling methods (static or insance) or accessing instance fields does not cause
.cctors to be run).
Next you need to know that there are two kinds of code generation that can happen
in the JIT: appdomain neutral and appdomain specialized. The difference
between these two kinds of code is how statics are handled. For appdomain
specific code, the address of a particular static variable is embeded in the
code. This makes it usable only for one appdomain (since every appdomain gets
a own copy of its statics). Appdomain neutral code calls a helper that looks
up static variables off of a thread local variable. Thus the same code can be
used by mulitple appdomains in the same process.
Generics also introduce a similar issue. Code for generic classes might be
specialised for a particular set of type arguments, or it could use helpers
to access data that depends on type parameters and thus be shared across several
instantiations of the generic type.
Thus there four cases
BeforeFieldInitCCtor - Unshared code.
Cctors are only called when static fields are fetched. At the time
the method that touches the static field is JITed (or fixed up in the
case of NGENed code), the .cctor is called.
BeforeFieldInitCCtor - Shared code.
Since the same code is used for multiple classes, the act of JITing
the code can not be used as a hook. However, it is also the case that
since the code is shared, it can not wire in a particular address for
the static and thus needs to use a helper that looks up the correct
address based on the thread ID. This helper does the .cctor check,
and thus no additional cctor logic is needed.
PreciseCCtor - Unshared code.
Any time a method is JITTed (or fixed up in the case of NGEN), a
cctor check for the class of the method being JITTed is done. In
addition the JIT inserts explicit checks before any static field
accesses. Instance methods and fields do NOT have hooks because
a .ctor method must be called before the instance can be created.
PreciseCctor - Shared code
.cctor checks are placed in the prolog of every .ctor and static
method. All methods that access static fields have an explicit
.cctor check before use. Again instance methods don't have hooks
because a .ctor would have to be called first.
Technically speaking, however the optimization of avoiding checks
on instance methods is flawed. It requires that a .ctor alwasy
preceed a call to an instance methods. This break down when
1) A NULL is passed to an instance method.
2) A .ctor does not call its superlcasses .ctor. THis allows
an instance to be created without necessarily calling all
the .cctors of all the superclasses. A virtual call can
then be made to a instance of a superclass without necessarily
calling the superclass's .cctor.
3) The class is a value class (which exists without a .ctor
being called.
Nevertheless, the cost of plugging these holes is considered to
high and the benefit is low.
----------------------------------------------------------------------
Thus the JIT's cctor responsibilities require it to check with the EE on every
static field access using 'initClass', and also to check CORINFO_FLG_RUN_CCTOR
before jitting any method to see if a .cctor check must be placed in the prolog.
CORINFO_FLG_NEEDS_INIT Only classes with NEEDS_INIT need to check possibly
place .cctor checks before static field accesses.
CORINFO_FLG_INITIALIZED Even if the class needs initing, it might be true
that the class has already been initialized. If
this bit is true, again, nothing needs to be done.
If false, initClass needs to be called
initClass For classes with CORINFO_FLG_NEEDS_INIT and not
CORINFO_FLG_INITIALIZED, initClass needs to be
called to determine if a CCTOR check is needed
(For class with beforeFieldInit semantics initclass
may run the cctor eagerly and returns that not
.cctor check is needed). If a .cctor check
is required the CORINFO_HELP_INITCLASS method has
to be called with a class handle parameter
(see embedGenericHandle)
CORINFO_FLG_RUN_CCTOR The jit is required to put CCTOR checks in the
prolog of methods with this attribute. Unfortunately
exactly what helper what helper is complicated
TODO describe
CORINFO_FLG_BEFOREFIELDINIT indicate the class has beforeFieldInit semantics.
The jit does not strictly need this information
however, it is valuable in optimizing static field
fetch helper calls. Helper call for classes with
BeforeFieldInit semantics can be hoisted before other
side effects where classes with precise .cctor
semantics do not allow this optimization.
Inlining also complicates things. Because the class could have precise semantics
it is also required that the inlining of any constructor or static method must
also do the CORINFO_FLG_NEEDS_INIT, CORINFO_FLG_INITIALIZED, initClass check.
(Instance methods don't have to because constructors always come first). In
addition inlined functions must also check the CORINFO_FLG_RUN_CCTOR bit. In
either case, the inliner has the option of inserting any required runtime check
or simply not inlining the function.
Finally, the JIT does has the option of skipping the CORINFO_FLG_NEEDS_INIT,
CORINFO_FLG_INITIALIZED, initClass check in the following cases
1) A static field access from an instance method of the same class
2) When inlining a method from and instance method of the same class.
The rationale here is that it can be assumed that if you are in an instance
method, the .cctor has already been called, and thus the check is not needed.
Historyically the getClassAttribs function did not have the method being
compiled passed to it so the EE could not fold this into its .cctor logic and
thus the JIT needed to do this. TODO: Now that this has changed, we should
have the EE do this.
-------------------------------------------------------------------------------
Static fields
The first 4 options are mutially exclusive
CORINFO_FLG_HELPER If the field has this set, then the JIT must call
getFieldHelper and call the returned helper with
the object ref (for an instance field) and a fieldDesc.
Note that this should be able to handle ANY field
so to get a JIT up quickly, it has the option of
using helper calls for all field access (and skip
the complexity below). Note that for statics it
is assumed that you will alwasy ask for the
ADDRESSS helper and to the fetch in the JIT.
CORINFO_FLG_SHARED_HELPER This is currently only used for static fields.
If this bit is set it means that the field is
feched by a helper call that takes a module
identifier (see getModuleDomainID) and a class
identifier (see getClassDomainID) as arguments.
The exact helper to call is determined by
getSharedStaticBaseHelper. The return value is
of this function is the base of all statics in
the module. The offset from getFieldOffset must
be added to this value to get the address of the
field itself. (see also CORINFO_FLG_STATIC_IN_HEAP).
CORINFO_FLG_GENERICS_STATIC This is currently only used for static fields
(of generic type). This function is intended to
be called with a Generic handle as a argument
(from embedGenericHandle). The exact helper to
call is determined by getSharedStaticBaseHelper.
The returned value is the base of all statics
in the class. The offset from getFieldOffset must
be added to this value to get the address of the
(see also CORINFO_FLG_STATIC_IN_HEAP).
CORINFO_FLG_TLS This indicate that the static field is a Windows
style Thread Local Static. (We also have managed
thread local statics, which work through the HELPER.
Support for this is considered legacy, and going
forward, the EE should
<NONE> This is a normal static field. Its address in
in memory is determined by getFieldAddress.
(see also CORINFO_FLG_STATIC_IN_HEAP).
This last field can modify any of the cases above except CORINFO_FLG_HELPER
CORINFO_FLG_STATIC_IN_HEAP This is currently only used for static fields
of value classes. If the field has this set then
after computing what would normally be the field,
what you actually get is a object poitner (that
must be reported to the GC) to a boxed version
of the value. Thus the actual field address is
computed by addr = (*addr+sizeof(OBJECTREF))
Instance fields
CORINFO_FLG_HELPER This is used if the class is MarshalByRef, which
means that the object might be a proxyt to the
real object in some other appdomain or process.
If the field has this set, then the JIT must call
getFieldHelper and call the returned helper with
the object ref. If the helper returned is helpers
that are for structures the args are as follows
CORINFO_HELP_GETFIELDSTRUCT - args are: retBuff, object, fieldDesc
CORINFO_HELP_SETFIELDSTRUCT - args are: object fieldDesc value
The other GET helpers take an object fieldDesc and return the value
The other SET helpers take an object fieldDesc and value
Note that unlike static fields there is no helper to take the address
of a field because in general there is no address for proxies (LDFLDA
is illegal on proxies).
CORINFO_FLG_EnC This is to support adding new field for edit and
continue. This field also indicates that a helper
is needed to access this field. However this helper
is always CORINFO_HELP_GETFIELDADDR, and this
helper always takes the object and field handle
and returns the address of the field. It is the
JIT's responcibility to do the fetch or set.
-------------------------------------------------------------------------------
TODO: Talk about initializing strutures before use
*******************************************************************************
*/
#ifndef _COR_INFO_H_
#define _COR_INFO_H_
#include <corhdr.h>
#include <specstrings.h>
// CorInfoHelpFunc defines the set of helpers (accessed via the ICorDynamicInfo::getHelperFtn())
// These helpers can be called by native code which executes in the runtime.
// Compilers can emit calls to these helpers.
//
// The signatures of the helpers are below (see RuntimeHelperArgumentCheck)
enum CorInfoHelpFunc
{
CORINFO_HELP_UNDEF, // invalid value. This should never be used
/* Arithmetic helpers */
CORINFO_HELP_LLSH,
CORINFO_HELP_LRSH,
CORINFO_HELP_LRSZ,
CORINFO_HELP_LMUL,
CORINFO_HELP_LMUL_OVF,
CORINFO_HELP_ULMUL_OVF,
CORINFO_HELP_LDIV,
CORINFO_HELP_LMOD,
CORINFO_HELP_ULDIV,
CORINFO_HELP_ULMOD,
CORINFO_HELP_ULNG2DBL, // Convert a unsigned in to a double
CORINFO_HELP_DBL2INT,
CORINFO_HELP_DBL2INT_OVF,
CORINFO_HELP_DBL2LNG,
CORINFO_HELP_DBL2LNG_OVF,
CORINFO_HELP_DBL2UINT,
CORINFO_HELP_DBL2UINT_OVF,
CORINFO_HELP_DBL2ULNG,
CORINFO_HELP_DBL2ULNG_OVF,
CORINFO_HELP_FLTREM,
CORINFO_HELP_DBLREM,
/* Allocating a new object. Always use ICorClassInfo::getNewHelper() to decide
which is the right helper to use to allocate an object of a given type. */
CORINFO_HELP_NEW_DIRECT, // new object
CORINFO_HELP_NEW_CROSSCONTEXT, // cross context new object
CORINFO_HELP_NEWFAST,
CORINFO_HELP_NEWSFAST, // allocator for small, non-finalizer, non-array object
CORINFO_HELP_NEWSFAST_ALIGN8, // allocator for small, non-finalizer, non-array object, 8 byte aligned
CORINFO_HELP_NEWSFAST_CHKRESTORE, // allocator like CORINFO_HELP_NEWSFAST, bails if type not restored.
CORINFO_HELP_NEW_SPECIALDIRECT, // direct but only if no context needed
CORINFO_HELP_NEW_MDARR, // multi-dim array helper (with or without lower bounds)
CORINFO_HELP_NEW_MDARR_NO_LBOUNDS, // multi-dim helper without lower bounds
CORINFO_HELP_NEWARR_1_DIRECT, // helper for any one dimensional array creation
CORINFO_HELP_NEWARR_1_OBJ, // optimized 1-D object arrays
CORINFO_HELP_NEWARR_1_VC, // optimized 1-D value class arrays
CORINFO_HELP_NEWARR_1_ALIGN8, // like VC, but aligns the array start
CORINFO_HELP_STRCNS, // create a new string literal
/* Object model */
CORINFO_HELP_INITCLASS, // Initialize class if not already initialized
CORINFO_HELP_INITINSTCLASS, // Initialize class for instantiated type
// Use ICorClassInfo::getIsInstanceOfHelper/getChkCastHelper to determine
// the right helper to use
CORINFO_HELP_ISINSTANCEOFINTERFACE, // Optimized helper for interfaces
CORINFO_HELP_ISINSTANCEOFARRAY, // Optimized helper for arrays
CORINFO_HELP_ISINSTANCEOFCLASS, // Optimized helper for classes
CORINFO_HELP_ISINSTANCEOFANY, // Slow helper for any type
CORINFO_HELP_CHKCASTINTERFACE,
CORINFO_HELP_CHKCASTARRAY,
CORINFO_HELP_CHKCASTCLASS,
CORINFO_HELP_CHKCASTANY,
CORINFO_HELP_CHKCASTCLASS_SPECIAL, // Optimized helper for classes. Assumes that the trivial cases
// has been taken care of by the inlined check
CORINFO_HELP_BOX,
CORINFO_HELP_BOX_NULLABLE, // special form of boxing for Nullable<T>
CORINFO_HELP_UNBOX,
CORINFO_HELP_UNBOX_NULLABLE, // special form of unboxing for Nullable<T>
CORINFO_HELP_GETREFANY, // Extract the byref from a TypedReference, checking that it is the expected type
CORINFO_HELP_ARRADDR_ST, // assign to element of object array with type-checking
CORINFO_HELP_LDELEMA_REF, // does a precise type comparision and returns address
/* Exceptions */
CORINFO_HELP_THROW, // Throw an exception object
CORINFO_HELP_RETHROW, // Rethrow the currently active exception
CORINFO_HELP_USER_BREAKPOINT, // For a user program to break to the debugger
CORINFO_HELP_RNGCHKFAIL, // array bounds check failed
CORINFO_HELP_OVERFLOW, // throw an overflow exception
CORINFO_HELP_INTERNALTHROW, // Support for really fast jit
CORINFO_HELP_INTERNALTHROW_FROM_HELPER,
CORINFO_HELP_VERIFICATION, // Throw a VerificationException
CORINFO_HELP_SEC_UNMGDCODE_EXCPT, // throw a security unmanaged code exception
CORINFO_HELP_FAIL_FAST, // Kill the process avoiding any exceptions or stack and data dependencies (use for GuardStack unsafe buffer checks)
CORINFO_HELP_ENDCATCH, // call back into the EE at the end of a catch block
/* Synchronization */
CORINFO_HELP_MON_ENTER,
CORINFO_HELP_MON_EXIT,
CORINFO_HELP_MON_ENTER_STATIC,
CORINFO_HELP_MON_EXIT_STATIC,
CORINFO_HELP_GETCLASSFROMMETHODPARAM, // Given a generics method handle, returns a class handle
CORINFO_HELP_GETSYNCFROMCLASSHANDLE, // Given a generics class handle, returns the sync monitor
// in its ManagedClassObject
/* Security callout support */
CORINFO_HELP_SECURITY_PROLOG, // Required if CORINFO_FLG_SECURITYCHECK is set, or CORINFO_FLG_NOSECURITYWRAP is not set
CORINFO_HELP_SECURITY_PROLOG_FRAMED, // Slow version of CORINFO_HELP_SECURITY_PROLOG. Used for instrumentation.
CORINFO_HELP_SECURITY_EPILOG, // Required if CORINFO_FLG_SECURITYCHECK is set, or CORINFO_FLG_NOSECURITYWRAP is not set
CORINFO_HELP_CALL_ALLOWED_BYSECURITY, // Callout to security - used if CORINFO_CALL_ALLOWED_BYSECURITY
/* Verification runtime callout support */
CORINFO_HELP_VERIFICATION_RUNTIME_CHECK, // Do a Demand for UnmanagedCode permission at runtime
/* GC support */
CORINFO_HELP_STOP_FOR_GC, // Call GC (force a GC)
CORINFO_HELP_POLL_GC, // Ask GC if it wants to collect
CORINFO_HELP_STRESS_GC, // Force a GC, but then update the JITTED code to be a noop call
CORINFO_HELP_CHECK_OBJ, // confirm that ECX is a valid object pointer (debugging only)
/* GC Write barrier support */
CORINFO_HELP_ASSIGN_REF, // universal helpers with F_CALL_CONV calling convention
CORINFO_HELP_CHECKED_ASSIGN_REF,
CORINFO_HELP_ASSIGN_BYREF, // EDI is byref, will do a MOVSD, incl. inc of ESI and EDI
// will trash ECX
CORINFO_HELP_ASSIGN_STRUCT,
CORINFO_HELP_SAFE_RETURNABLE_BYREF, // Check that a byref is safe to be returned from a call by ensuring that it points into the GC heap
#ifdef _X86_
CORINFO_HELP_ASSIGN_REF_EAX, // EAX hold GC ptr, want do a 'mov [EDX], EAX' and inform GC
CORINFO_HELP_ASSIGN_REF_EBX, // EBX hold GC ptr, want do a 'mov [EDX], EBX' and inform GC
CORINFO_HELP_ASSIGN_REF_ECX, // ECX hold GC ptr, want do a 'mov [EDX], ECX' and inform GC
CORINFO_HELP_ASSIGN_REF_ESI, // ESI hold GC ptr, want do a 'mov [EDX], ESI' and inform GC
CORINFO_HELP_ASSIGN_REF_EDI, // EDI hold GC ptr, want do a 'mov [EDX], EDI' and inform GC
CORINFO_HELP_ASSIGN_REF_EBP, // EBP hold GC ptr, want do a 'mov [EDX], EBP' and inform GC
CORINFO_HELP_CHECKED_ASSIGN_REF_EAX, // These are the same as ASSIGN_REF above ...
CORINFO_HELP_CHECKED_ASSIGN_REF_EBX, // ... but checks if EDX points to heap.
CORINFO_HELP_CHECKED_ASSIGN_REF_ECX,
CORINFO_HELP_CHECKED_ASSIGN_REF_ESI,
CORINFO_HELP_CHECKED_ASSIGN_REF_EDI,
CORINFO_HELP_CHECKED_ASSIGN_REF_EBP,
#endif
/* Accessing fields */
// For COM object support (using COM get/set routines to update object)
// and EnC and cross-context support
CORINFO_HELP_GETFIELD32,
CORINFO_HELP_SETFIELD32,
CORINFO_HELP_GETFIELD64,
CORINFO_HELP_SETFIELD64,
CORINFO_HELP_GETFIELDOBJ,
CORINFO_HELP_SETFIELDOBJ,
CORINFO_HELP_GETFIELDSTRUCT,
CORINFO_HELP_SETFIELDSTRUCT,
CORINFO_HELP_GETFIELDFLOAT,
CORINFO_HELP_SETFIELDFLOAT,
CORINFO_HELP_GETFIELDDOUBLE,
CORINFO_HELP_SETFIELDDOUBLE,
CORINFO_HELP_GETFIELDADDR,
CORINFO_HELP_GETSTATICFIELDADDR,
CORINFO_HELP_GETGENERICS_GCSTATIC_BASE,
CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE,
// Use ICorClassInfo::getSharedStaticBaseHelper/getSharedCCtorHelper
// to determine the right helper to use
CORINFO_HELP_GETSHARED_GCSTATIC_BASE,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE,
CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS,
/* Debugger */
CORINFO_HELP_DBG_IS_JUST_MY_CODE, // Check if this is "JustMyCode" and needs to be stepped through.
/* Profiling enter/leave probe addresses */
CORINFO_HELP_PROF_FCN_ENTER, // record the entry to a method (caller)
CORINFO_HELP_PROF_FCN_LEAVE, // record the completion of current method (caller)
CORINFO_HELP_PROF_FCN_TAILCALL, // record the completionof current method through tailcall (caller)
/* Miscellaneous */
CORINFO_HELP_BBT_FCN_ENTER, // record the entry to a method for collecting Tuning data
CORINFO_HELP_PINVOKE_CALLI, // Indirect pinvoke call
CORINFO_HELP_TAILCALL, // Perform a tail call
CORINFO_HELP_GET_THREAD_FIELD_ADDR_PRIMITIVE,
CORINFO_HELP_GET_THREAD_FIELD_ADDR_OBJREF,
CORINFO_HELP_GET_THREAD,
CORINFO_HELP_INIT_PINVOKE_FRAME, // initialize an inlined PInvoke Frame for the JIT-compiler
CORINFO_HELP_FAST_PINVOKE, // fast PInvoke helper
CORINFO_HELP_CHECK_PINVOKE_DOMAIN, // check which domain the pinvoke call is in
CORINFO_HELP_MEMSET, // Init block of memory
CORINFO_HELP_MEMCPY, // Copy block of memory
CORINFO_HELP_RUNTIMEHANDLE, // determine a type/field/method handle at run-time
CORINFO_HELP_VIRTUAL_FUNC_PTR, // look up a virtual method at run-time
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
*
* Start of Machine-specific helpers. All new common JIT helpers
* should be added before here
*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
#if !CPU_HAS_FP_SUPPORT
//
// Some architectures need helpers for FP support
//
// Keep these at the end of the enum
//
CORINFO_HELP_R4_NEG,
CORINFO_HELP_R8_NEG,
CORINFO_HELP_R4_ADD,
CORINFO_HELP_R8_ADD,
CORINFO_HELP_R4_SUB,
CORINFO_HELP_R8_SUB,
CORINFO_HELP_R4_MUL,
CORINFO_HELP_R8_MUL,
CORINFO_HELP_R4_DIV,
CORINFO_HELP_R8_DIV,
CORINFO_HELP_R4_EQ,
CORINFO_HELP_R8_EQ,
CORINFO_HELP_R4_NE,
CORINFO_HELP_R8_NE,
CORINFO_HELP_R4_LT,
CORINFO_HELP_R8_LT,
CORINFO_HELP_R4_LE,
CORINFO_HELP_R8_LE,
CORINFO_HELP_R4_GE,
CORINFO_HELP_R8_GE,
CORINFO_HELP_R4_GT,
CORINFO_HELP_R8_GT,
CORINFO_HELP_R8_TO_I4,
CORINFO_HELP_R8_TO_I8,
CORINFO_HELP_R8_TO_R4,
CORINFO_HELP_R4_TO_I4,
CORINFO_HELP_R4_TO_I8,
CORINFO_HELP_R4_TO_R8,
CORINFO_HELP_I4_TO_R4,
CORINFO_HELP_I4_TO_R8,
CORINFO_HELP_I8_TO_R4,
CORINFO_HELP_I8_TO_R8,
CORINFO_HELP_U4_TO_R4,
CORINFO_HELP_U4_TO_R8,
CORINFO_HELP_U8_TO_R4,
CORINFO_HELP_U8_TO_R8,
#endif
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
*
* Don't add new JIT helpers here! Add them before the machine-specific
* helpers.
*
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
CORINFO_HELP_COUNT
};
// The enumeration is returned in 'getSig','getType', getArgType methods
enum CorInfoType
{
CORINFO_TYPE_UNDEF = 0x0,
CORINFO_TYPE_VOID = 0x1,
CORINFO_TYPE_BOOL = 0x2,
CORINFO_TYPE_CHAR = 0x3,
CORINFO_TYPE_BYTE = 0x4,
CORINFO_TYPE_UBYTE = 0x5,
CORINFO_TYPE_SHORT = 0x6,
CORINFO_TYPE_USHORT = 0x7,
CORINFO_TYPE_INT = 0x8,
CORINFO_TYPE_UINT = 0x9,
CORINFO_TYPE_LONG = 0xa,
CORINFO_TYPE_ULONG = 0xb,
CORINFO_TYPE_NATIVEINT = 0xc,
CORINFO_TYPE_NATIVEUINT = 0xd,
CORINFO_TYPE_FLOAT = 0xe,
CORINFO_TYPE_DOUBLE = 0xf,
CORINFO_TYPE_STRING = 0x10, // Not used, should remove
CORINFO_TYPE_PTR = 0x11,
CORINFO_TYPE_BYREF = 0x12,
CORINFO_TYPE_VALUECLASS = 0x13,
CORINFO_TYPE_CLASS = 0x14,
CORINFO_TYPE_REFANY = 0x15,
// CORINFO_TYPE_VAR is for a generic type variable.
// Generic type variables only appear when the JIT is doing
// verification (not NOT compilation) of generic code
// for the EE, in which case we're running
// the JIT in "import only" mode.
CORINFO_TYPE_VAR = 0x16,
CORINFO_TYPE_COUNT, // number of jit types
};
enum CorInfoTypeWithMod
{
CORINFO_TYPE_MASK = 0x3F, // lower 6 bits are type mask
CORINFO_TYPE_MOD_PINNED = 0x40, // can be applied to CLASS, or BYREF to indiate pinned
};
inline CorInfoType strip(CorInfoTypeWithMod val) {
return CorInfoType(val & CORINFO_TYPE_MASK);
}
// The enumeration is returned in 'getSig'
enum CorInfoCallConv
{
// These correspond to CorCallingConvention
CORINFO_CALLCONV_DEFAULT = 0x0,
CORINFO_CALLCONV_C = 0x1,
CORINFO_CALLCONV_STDCALL = 0x2,
CORINFO_CALLCONV_THISCALL = 0x3,
CORINFO_CALLCONV_FASTCALL = 0x4,
CORINFO_CALLCONV_VARARG = 0x5,
CORINFO_CALLCONV_FIELD = 0x6,
CORINFO_CALLCONV_LOCAL_SIG = 0x7,
CORINFO_CALLCONV_PROPERTY = 0x8,
CORINFO_CALLCONV_NATIVEVARARG = 0xb, // used ONLY for 64bit PInvoke vararg calls
CORINFO_CALLCONV_MASK = 0x0f, // Calling convention is bottom 4 bits
CORINFO_CALLCONV_GENERIC = 0x10,
CORINFO_CALLCONV_HASTHIS = 0x20,
CORINFO_CALLCONV_EXPLICITTHIS=0x40,
CORINFO_CALLCONV_PARAMTYPE = 0x80, // Passed last. Same as CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG
};
enum CorInfoUnmanagedCallConv
{
// These correspond to CorUnmanagedCallingConvention
CORINFO_UNMANAGED_CALLCONV_UNKNOWN,
CORINFO_UNMANAGED_CALLCONV_C,
CORINFO_UNMANAGED_CALLCONV_STDCALL,
CORINFO_UNMANAGED_CALLCONV_THISCALL,
CORINFO_UNMANAGED_CALLCONV_FASTCALL
};
// These are returned from getMethodOptions
enum CorInfoOptions
{
CORINFO_OPT_INIT_LOCALS = 0x00000010, // zero initialize all variables
CORINFO_GENERICS_CTXT_FROM_THIS = 0x00000020, // is this shared generic code that access the generic context from the this pointer? If so, then if the method has SEH then the 'this' pointer must always be reported and kept alive.
CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG = 0x00000040, // is this shared generic code that access the generic context from the ParamTypeArg? If so, then if the method has SEH then the 'ParamTypeArg' must always be reported and kept alive. Same as CORINFO_CALLCONV_PARAMTYPE
CORINFO_GENERICS_CTXT_MASK = (CORINFO_GENERICS_CTXT_FROM_THIS |
CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG),
CORINFO_GENERICS_CTXT_KEEP_ALIVE = 0x00000080, // Keep the generics context alive throughout the method even if there is no explicit use, and report its location to the CLR
};
// These are potential return values for ICorFieldInfo::getFieldCategory
// If the JIT receives a category that it doesn't know about or doesn't
// care to optimize specially for, it should treat it as CORINFO_FIELDCATEGORY_UNKNOWN.
enum CorInfoFieldCategory
{
CORINFO_FIELDCATEGORY_NORMAL, // normal GC object
CORINFO_FIELDCATEGORY_UNKNOWN, // always call field get/set helpers
CORINFO_FIELDCATEGORY_I1_I1, // indirect access: fetch 1 byte
CORINFO_FIELDCATEGORY_I2_I2, // indirect access: fetch 2 bytes
CORINFO_FIELDCATEGORY_I4_I4, // indirect access: fetch 4 bytes
CORINFO_FIELDCATEGORY_I8_I8, // indirect access: fetch 8 bytes
CORINFO_FIELDCATEGORY_BOOLEAN_BOOL, // boolean to 4-byte BOOL
CORINFO_FIELDCATEGORY_CHAR_CHAR,// (Unicode) "char" to (ansi) CHAR
CORINFO_FIELDCATEGORY_UI1_UI1, // indirect access: fetch 1 byte
CORINFO_FIELDCATEGORY_UI2_UI2, // indirect access: fetch 2 bytes
CORINFO_FIELDCATEGORY_UI4_UI4, // indirect access: fetch 4 bytes
CORINFO_FIELDCATEGORY_UI8_UI8, // indirect access: fetch 8 bytes
};
// these are the attribute flags for fields and methods (getMethodAttribs)
enum CorInfoFlag
{
// These values are an identical mapping from the resp.
// access_flag bits
CORINFO_FLG_PUBLIC = 0x00000001,
CORINFO_FLG_PRIVATE = 0x00000002,
CORINFO_FLG_PROTECTED = 0x00000004,
CORINFO_FLG_STATIC = 0x00000008,
CORINFO_FLG_FINAL = 0x00000010,
CORINFO_FLG_SYNCH = 0x00000020,
CORINFO_FLG_VIRTUAL = 0x00000040,
// CORINFO_FLG_AGILE = 0x00000080,
CORINFO_FLG_NATIVE = 0x00000100,
CORINFO_FLG_NOTREMOTABLE = 0x00000200,
CORINFO_FLG_ABSTRACT = 0x00000400,
CORINFO_FLG_EnC = 0x00000800, // member was added by Edit'n'Continue
// These are internal flags that can only be on methods
CORINFO_FLG_IMPORT = 0x00020000, // method is an imported symbol
CORINFO_FLG_DELEGATE_INVOKE = 0x00040000, // "Delegate
// CORINFO_FLG_UNCHECKEDPINVOKE = 0x00080000, // Is a P/Invoke call that requires no security checks
CORINFO_FLG_PINVOKE = 0x00080000, // Is a P/Invoke call
CORINFO_FLG_SECURITYCHECK = 0x00100000, // Is one of the security routines that does a stackwalk (e.g. Assert, Demand)
CORINFO_FLG_NOGCCHECK = 0x00200000, // This method is FCALL that has no GC check. Don't put alone in loops
CORINFO_FLG_INTRINSIC = 0x00400000, // This method MAY have an intrinsic ID
CORINFO_FLG_CONSTRUCTOR = 0x00800000, // method is an instance or type initializer
CORINFO_FLG_RUN_CCTOR = 0x01000000, // This method must run the class cctor as it has PreciseInit semantics
CORINFO_FLG_SHAREDINST = 0x02000000, // the code for this method is shared between different generic instantiations
CORINFO_FLG_NOSECURITYWRAP = 0x04000000, // method requires no security checks
// These are the valid bits that a jitcompiler can pass to setJitterMethodFlags for
// non-native methods only; a jitcompiler can access these flags using getMethodFlags.
CORINFO_FLG_JITTERFLAGSMASK = 0xF0000000,
CORINFO_FLG_DONT_INLINE = 0x10000000, // The method should not be inlined
// CORINFO_FLG_INLINED = 0x20000000,
// CORINFO_FLG_NOSIDEEFFECTS = 0x40000000,
// These are internal flags that can only be on Fields
CORINFO_FLG_HELPER = 0x00010000, // field accessed via ordinary helper calls
CORINFO_FLG_TLS = 0x00020000, // This variable accesses thread local store.
CORINFO_FLG_SHARED_HELPER = 0x00040000, // field is access via optimized shared helper
CORINFO_FLG_STATIC_IN_HEAP = 0x00080000, // This static field is in the GC heap as a boxed object
CORINFO_FLG_GENERICS_STATIC = 0x00100000, // This static field is being accessed from shared code. Use ICorClassInfo::getSharedStaticBaseHelper() to access it
CORINFO_FLG_UNMANAGED = 0x00200000, // is this an unmanaged value class?
CORINFO_FLG_SAFESTATIC_BYREF_RETURN = 0x00800000, // Field can be returned safely (has GC heap lifetime)
CORINFO_FLG_NONVERIFIABLYOVERLAPS = 0x01000000, // Field overlaps a different field
// These are internal flags that can only be on Classes
CORINFO_FLG_VALUECLASS = 0x00010000, // is the class a value class
CORINFO_FLG_INITIALIZED = 0x00020000, // The class has been cctor'ed
CORINFO_FLG_VAROBJSIZE = 0x00040000, // the object size varies depending of constructor args
CORINFO_FLG_ARRAY = 0x00080000, // class is an array class (initialized differently)
CORINFO_FLG_ALIGN8_HINT = 0x00100000, // align to 8 bytes if posible
CORINFO_FLG_INTERFACE = 0x00200000, // it is an interface
CORINFO_FLG_CONTEXTFUL = 0x00400000, // is this a contextful class?
CORINFO_FLG_CONTAINS_GC_PTR = 0x01000000, // does the class contain a gc ptr ?
CORINFO_FLG_DELEGATE = 0x02000000, // is this a subclass of delegate or multicast delegate ?
CORINFO_FLG_MARSHAL_BYREF = 0x04000000, // is this a subclass of MarshalByRef ?
CORINFO_FLG_CONTAINS_STACK_PTR = 0x08000000, // This class has a stack pointer inside it
CORINFO_FLG_NEEDS_INIT = 0x10000000, // Access to this type should check ICorClassInfo::initClass() and then add JIT hooks for the cctor.
CORINFO_FLG_BEFOREFIELDINIT = 0x20000000, // Additional flexibility for when to run .cctor
CORINFO_FLG_GENERIC_TYPE_VARIABLE = 0x40000000, // This is really a handle for a variable type
CORINFO_FLG_UNSAFE_VALUECLASS = 0x80000000, // Unsafe (C++'s /GS) value type
};
// Flags computed by a runtime compiler
enum CorInfoMethodRuntimeFlags
{
CORINFO_FLG_BAD_INLINEE = 0x00000001, // The method is not suitable for inlining
CORINFO_FLG_VERIFIABLE = 0x00000002, // The method has verifiable code
CORINFO_FLG_UNVERIFIABLE = 0x00000004, // The method has unverifiable code
};
enum CORINFO_ACCESS_FLAGS
{
CORINFO_ACCESS_ANY = 0x0000, // Normal access
CORINFO_ACCESS_THIS = 0x0001, // Accessed via the this reference
CORINFO_ACCESS_UNWRAP = 0x0002, // Accessed via an unwrap reference
CORINFO_ACCESS_NONNULL = 0x0004, // Instance is guaranteed non-null
CORINFO_ACCESS_DIRECT = 0x0008, // Set by ngen if it already checked that the method can be called directly
// using ICorMethodInfo::canSkipMethodPreparation
CORINFO_ACCESS_STABLE = 0x0010, // Set by ngen to request call via stable entrypoint
};
// These are the flags set on an CORINFO_EH_CLAUSE
enum CORINFO_EH_CLAUSE_FLAGS
{
CORINFO_EH_CLAUSE_NONE = 0,
CORINFO_EH_CLAUSE_FILTER = 0x0001, // If this bit is on, then this EH entry is for a filter
CORINFO_EH_CLAUSE_FINALLY = 0x0002, // This clause is a finally clause
CORINFO_EH_CLAUSE_FAULT = 0x0004, // This clause is a fault clause
};
// This enumeration is passed to InternalThrow
enum CorInfoException
{
CORINFO_NullReferenceException,
CORINFO_DivideByZeroException,
CORINFO_InvalidCastException,
CORINFO_IndexOutOfRangeException,
CORINFO_OverflowException,
CORINFO_SynchronizationLockException,
CORINFO_ArrayTypeMismatchException,
CORINFO_RankException,
CORINFO_ArgumentNullException,
CORINFO_ArgumentException,
CORINFO_Exception_Count,
};
// This enumeration is returned by getIntrinsicID. Methods corresponding to
// these values will have "well-known" specified behavior. Calls to these
// methods could be replaced with inlined code corresponding to the
// specified behavior (without having to examine the IL beforehand).
enum CorInfoIntrinsics
{
CORINFO_INTRINSIC_Sin,
CORINFO_INTRINSIC_Cos,
CORINFO_INTRINSIC_Sqrt,
CORINFO_INTRINSIC_Abs,
CORINFO_INTRINSIC_Round,
CORINFO_INTRINSIC_GetChar, // fetch character out of string
CORINFO_INTRINSIC_Array_GetDimLength, // Get number of elements in a given dimension of an array
CORINFO_INTRINSIC_Array_GetLengthTotal, // Get total number of elements in an array
CORINFO_INTRINSIC_Array_Get, // Get the value of an element in an array
CORINFO_INTRINSIC_Array_Address, // Get the address of an element in an array
CORINFO_INTRINSIC_Array_Set, // Set the value of an element in an array
CORINFO_INTRINSIC_StringGetChar, // fetch character out of string
CORINFO_INTRINSIC_StringLength, // get the length
CORINFO_INTRINSIC_InitializeArray, // initialize an array from static data
CORINFO_INTRINSIC_Type_TypeHandle_get,
CORINFO_INTRINSIC_GetClassFromHandle,
CORINFO_INTRINSIC_Object_GetType,
CORINFO_INTRINSIC_Count,
CORINFO_INTRINSIC_Illegal = -1, // Not a true intrinsic,
};
// Can a value be accessed directly from JITed code.
enum InfoAccessType
{
IAT_VALUE, // The info value is directly available
IAT_PVALUE, // The value needs to be accessed via an indirection
IAT_PPVALUE // The value needs to be accessed via a double indirection
};
// Can a value be accessed directly from JITed code.
enum InfoAccessModule
{
IAM_UNKNOWN_MODULE, // The target module for the info value is not known
IAM_CURRENT_MODULE, // The target module for the info value is the current module
IAM_EXTERNAL_MODULE, // The target module for the info value is an external module
};
enum CorInfoGCType
{
TYPE_GC_NONE, // no embedded objectrefs
TYPE_GC_REF, // Is an object ref
TYPE_GC_BYREF, // Is an interior pointer - promote it but don't scan it
TYPE_GC_OTHER // requires type-specific treatment
};
enum CorInfoClassId
{
CLASSID_SYSTEM_OBJECT,
CLASSID_TYPED_BYREF,
CLASSID_TYPE_HANDLE,
CLASSID_FIELD_HANDLE,
CLASSID_METHOD_HANDLE,
CLASSID_STRING,
CLASSID_ARGUMENT_HANDLE,
};
enum CorInfoFieldAccess
{
CORINFO_GET,
CORINFO_SET,
CORINFO_ADDRESS,
};
enum CorInfoInline
{
INLINE_PASS = 0, // Inlining OK
// failures are negative
INLINE_FAIL = -1, // Inlining not OK for this case only
INLINE_NEVER = -2, // This method should never be inlined, regardless of context
};
enum CorInfoInlineRestrictions
{
INLINE_RESPECT_BOUNDARY = 0x00000001, // You can inline if there are no calls from the method being inlined
INLINE_NO_CALLEE_LDSTR = 0x00000002, // You can inline only if you guarantee that if inlinee does an ldstr
// inlinee's module will never see that string (by any means).
// This is due to how we implement the NoStringInterningAttribute
// (by reusing the fixup table).
INLINE_SAME_THIS = 0x00000004, // You can inline only if the callee is on the same this reference as caller
};
enum CorInfoIsCallAllowedResult
{
CORINFO_CALL_ALLOWED = 0, // Call allowed
CORINFO_CALL_ILLEGAL = 1, // Call not allowed
CORINFO_CALL_RUNTIME_CHECK = 2, // Ask at runtime whether to allow the call or not
};
enum CORINFO_CALL_ALLOWED_FLAGS
{
CORINFO_CALL_ALLOWED_NONE = 0x0000, // Invalid value
CORINFO_CALL_ALLOWED_BYSECURITY = 0x0001, // Callout to security permission
};
struct CORINFO_CALL_ALLOWED_INFO
{
CORINFO_CALL_ALLOWED_FLAGS mask; // Which callout(s) are needed?
void * context; // The context for the callout?
};
enum CorInfoCanSkipVerificationResult
{
CORINFO_VERIFICATION_CANNOT_SKIP = 0, // Cannot skip verification during jit time.
CORINFO_VERIFICATION_CAN_SKIP = 1, // Can skip verification during jit time.
CORINFO_VERIFICATION_RUNTIME_CHECK = 2, // Skip verification during jit time,
// but need to insert a callout to the VM to ask during runtime
// whether to skip verification or not.
};
// Reason codes for making indirect calls
#define INDIRECT_CALL_REASONS() \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_UNKNOWN) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_EXOTIC) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_PINVOKE) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_GENERIC) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_NO_CODE) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_FIXUPS) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_STUB) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_REMOTING) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_CER) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_CCTOR_TRIGGER) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_RESTORE_METHOD) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_RESTORE_FIRST_CALL) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_RESTORE_VALUE_TYPE) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_RESTORE) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_CANT_PATCH) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_PROFILING) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_DISABLED) \
INDIRECT_CALL_REASON_FUNC(CORINFO_INDIRECT_CALL_OTHER_LOADER_MODULE) \
enum CorInfoIndirectCallReason
{
#undef INDIRECT_CALL_REASON_FUNC
#define INDIRECT_CALL_REASON_FUNC(x) x,
INDIRECT_CALL_REASONS()
#undef INDIRECT_CALL_REASON_FUNC
CORINFO_INDIRECT_CALL_COUNT
};
// This is for use when the JIT is compiling an instantiation
// of generic code. The JIT needs to know if the generic code itself
// (which can be verified once and for all independently of the
// instantiations) passed verification.
enum CorInfoInstantiationVerification
{
// The method is NOT a concrete instantiation (eg. List<int>.Add()) of a method
// in a generic class or a generic method. It is either the typical instantiation
// (eg. List<T>.Add()) or entirely non-generic.
INSTVER_NOT_INSTANTIATION = 0,
// The method is an instantiation of a method in a generic class or a generic method,
// and the generic class was successfully verified
INSTVER_GENERIC_PASSED_VERIFICATION = 1,
// The method is an instantiation of a method in a generic class or a generic method,
// and the generic class failed verification
INSTVER_GENERIC_FAILED_VERIFICATION = 2,
};
inline bool dontInline(CorInfoInline val) {
return(val < 0);
}
// Cookie types consumed by the code generator (these are opaque values
// not inspected by the code generator):
typedef struct CORINFO_ASSEMBLY_STRUCT_* CORINFO_ASSEMBLY_HANDLE;
typedef struct CORINFO_MODULE_STRUCT_* CORINFO_MODULE_HANDLE;
typedef struct CORINFO_DEPENDENCY_STRUCT_* CORINFO_DEPENDENCY_HANDLE;
typedef struct CORINFO_CLASS_STRUCT_* CORINFO_CLASS_HANDLE;
typedef struct CORINFO_METHOD_STRUCT_* CORINFO_METHOD_HANDLE;
typedef struct CORINFO_FIELD_STRUCT_* CORINFO_FIELD_HANDLE;
typedef struct CORINFO_ARG_LIST_STRUCT_* CORINFO_ARG_LIST_HANDLE; // represents a list of argument types
typedef struct CORINFO_SIG_STRUCT_* CORINFO_SIG_HANDLE; // represents the whole list
typedef struct CORINFO_JUST_MY_CODE_HANDLE_*CORINFO_JUST_MY_CODE_HANDLE;
typedef struct CORINFO_PROFILING_STRUCT_* CORINFO_PROFILING_HANDLE; // a handle guaranteed to be unique per process
typedef DWORD* CORINFO_SHAREDMODULEID_HANDLE;
typedef struct CORINFO_GENERIC_STRUCT_* CORINFO_GENERIC_HANDLE; // a generic handle (could be any of the above)
// what is actually passed on the varargs call
typedef struct CORINFO_VarArgInfo * CORINFO_VARARGS_HANDLE;
// Generic tokens are resolved with respect to a context, which is usually the method
// being compiled. The CORINFO_CONTEXT_HANDLE indicates which exact instantiation
// (or the open instantiation) is being referred to.
// CORINFO_CONTEXT_HANDLE is more tightly scoped than CORINFO_MODULE_HANDLE. For cases
// where the exact instantiation does not matter, CORINFO_MODULE_HANDLE is used.
typedef CORINFO_METHOD_HANDLE CORINFO_CONTEXT_HANDLE;
// Bit-twiddling of contexts assumes word-alignment of method handles and type handles
// If this ever changes, some other encoding will be needed
enum CorInfoContextFlags
{
CORINFO_CONTEXTFLAGS_METHOD = 0x00, // CORINFO_CONTEXT_HANDLE is really a CORINFO_METHOD_HANDLE
CORINFO_CONTEXTFLAGS_CLASS = 0x01, // CORINFO_CONTEXT_HANDLE is really a CORINFO_CLASS_HANDLE
CORINFO_CONTEXTFLAGS_MASK = 0x01
};
#define MAKE_CLASSCONTEXT(c) (CORINFO_CONTEXT_HANDLE((size_t) (c) | CORINFO_CONTEXTFLAGS_CLASS))
#define MAKE_METHODCONTEXT(m) (CORINFO_CONTEXT_HANDLE((size_t) (m) | CORINFO_CONTEXTFLAGS_METHOD))
enum CorInfoSigInfoFlags
{
CORINFO_SIGFLAG_IS_LOCAL_SIG = 0x01,
CORINFO_SIGFLAG_IL_STUB = 0x02,
};
struct CORINFO_SIG_INST
{
unsigned classInstCount;
CORINFO_CLASS_HANDLE * classInst; // (representative, not exact) instantiation for class type variables in signature
unsigned methInstCount;
CORINFO_CLASS_HANDLE * methInst; // (representative, not exact) instantiation for method type variables in signature
};
struct CORINFO_SIG_INFO
{
CorInfoCallConv callConv;
CORINFO_CLASS_HANDLE retTypeClass; // if the return type is a value class, this is its handle (enums are normalized)
CORINFO_CLASS_HANDLE retTypeSigClass;// returns the value class as it is in the sig (enums are not converted to primitives)
CorInfoType retType : 8;
unsigned flags : 8; // used by IL stubs code
unsigned numArgs : 16;
struct CORINFO_SIG_INST sigInst; // information about how type variables are being instantiated in generic code
CORINFO_ARG_LIST_HANDLE args;
CORINFO_SIG_HANDLE sig;
CORINFO_MODULE_HANDLE scope; // passed to getArgClass
mdToken token;
bool hasRetBuffArg() { return retType == CORINFO_TYPE_VALUECLASS || retType == CORINFO_TYPE_REFANY; }
CorInfoCallConv getCallConv() { return CorInfoCallConv((callConv & CORINFO_CALLCONV_MASK)); }
bool hasThis() { return ((callConv & CORINFO_CALLCONV_HASTHIS) != 0); }
unsigned totalILArgs() { return (numArgs + hasThis()); }
unsigned totalNativeArgs() { return (totalILArgs() + hasRetBuffArg()); }
bool isVarArg() { return ((getCallConv() == CORINFO_CALLCONV_VARARG) || (getCallConv() == CORINFO_CALLCONV_NATIVEVARARG)); }
bool hasTypeArg() { return ((callConv & CORINFO_CALLCONV_PARAMTYPE) != 0); }
};
struct CORINFO_METHOD_INFO
{
CORINFO_METHOD_HANDLE ftn;
CORINFO_MODULE_HANDLE scope;
BYTE * ILCode;
unsigned ILCodeSize;
unsigned short maxStack;
unsigned short EHcount;
CorInfoOptions options;
CORINFO_SIG_INFO args;
CORINFO_SIG_INFO locals;
};
//----------------------------------------------------------------------------
// Looking up handles and addresses.
//
// When the JIT requests a handle, the EE may direct the JIT that it must
// access the handle in a variety of ways. These are packed as
// CORINFO_CONST_LOOKUP
// or CORINFO_LOOKUP (contains either a CORINFO_CONST_LOOKUP or a CORINFO_RUNTIME_LOOKUP)
//
// Constant Lookups v. Runtime Lookups (i.e. when will Runtime Lookups be generated?)
// -----------------------------------------------------------------------------------
//
// CORINFO_LOOKUP_KIND is part of the result type of embedGenericHandle,
// getVirtualCallInfo and any other functions that may require a
// runtime lookup when compiling shared generic code.
//
// CORINFO_LOOKUP_KIND indicates whether a particular token in the instruction stream can be:
// (a) Mapped to a handle (type, field or method) at compile-time (!needsRuntimeLookup)
// (b) Must be looked up at run-time, and if so which runtime lookup technique should be used (see below)
//
// If the JIT or EE does not support code sharing for generic code, then
// all CORINFO_LOOKUP results will be "constant lookups", i.e.
// the needsRuntimeLookup of CORINFO_LOOKUP.lookupKind.needsRuntimeLookup
// will be false.
//
// Constant Lookups
// ----------------
//
// Constant Lookups are either:
// IAT_VALUE: immediate (relocatable) values,
// IAT_PVALUE: immediate values access via an indirection through an immediate (relocatable) address
// IAT_PPVALUE: immediate values access via a double indirection through an immediate (relocatable) address
//
// Runtime Lookups
// ---------------
//
// CORINFO_LOOKUP_KIND is part of the result type of embedGenericHandle,
// getVirtualCallInfo and any other functions that may require a
// runtime lookup when compiling shared generic code.
//
// CORINFO_LOOKUP_KIND indicates whether a particular token in the instruction stream can be:
// (a) Mapped to a handle (type, field or method) at compile-time (!needsRuntimeLookup)
// (b) Must be looked up at run-time using the class dictionary
// stored in the vtable of the this pointer (needsRuntimeLookup && THISOBJ)
// (c) Must be looked up at run-time using the method dictionary
// stored in the method descriptor parameter passed to a generic
// method (needsRuntimeLookup && METHODPARAM)
// (d) Must be looked up at run-time using the class dictionary stored
// in the vtable parameter passed to a method in a generic
// struct (needsRuntimeLookup && CLASSPARAM)
struct CORINFO_CONST_LOOKUP
{
union
{
CORINFO_GENERIC_HANDLE handle;
void * addr;
};
InfoAccessType accessType;
InfoAccessModule accessModule;
};
enum CORINFO_RUNTIME_LOOKUP_KIND
{
CORINFO_LOOKUP_THISOBJ,
CORINFO_LOOKUP_METHODPARAM,
CORINFO_LOOKUP_CLASSPARAM,
};
struct CORINFO_LOOKUP_KIND
{
bool needsRuntimeLookup;
CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind;
} ;
// CORINFO_RUNTIME_LOOKUP indicates the details of the runtime lookup
// operation to be performed.
//
// CORINFO_MAXINDIRECTIONS is the maximum number of
// indirections used by runtime lookups.
// This accounts for up to 2 indirections to get at a dictionary followed by a possible spill slot
#define CORINFO_MAXINDIRECTIONS 4
#define CORINFO_USEHELPER ((WORD) 0xffff)
struct CORINFO_RUNTIME_LOOKUP
{
// This are the tokens you must pass back to the runtime lookup helper
DWORD token1;
DWORD token2;
// Here is the helper you must call. At the moment it is always
// CORINFO_HELP_RUNTIMEHANDLE.
CorInfoHelpFunc helper;
// Number of indirections to get there
// CORINFO_USEHELPER = don't know how to get it, so use helper function at run-time instead
// 0 = use the this pointer itself (e.g. token is C<!0> inside code in sealed class C)
// or method desc itself (e.g. token is method void M::mymeth<!!0>() inside code in M::mymeth)
// Otherwise, follow each byte-offset stored in the "offsets[]" array (may be negative)
WORD indirections;
// If set, test for null and branch to helper if null
WORD testForNull;
WORD offsets[CORINFO_MAXINDIRECTIONS];
} ;
// Result of calling embedGenericHandle
struct CORINFO_LOOKUP
{
CORINFO_LOOKUP_KIND lookupKind;
// If kind.needsRuntimeLookup then this indicates how to do the lookup
CORINFO_RUNTIME_LOOKUP runtimeLookup;
// If the handle is obtained at compile-time, then this handle is the "exact" handle (class, method, or field)
// Otherwise, it's a representative... If accessType is
// IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address
// IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle
// IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle
CORINFO_CONST_LOOKUP constLookup;
};
// Flags that are combined with a type token in calls to embedGenericHandle, findMethod, findClass and CORINFO_HELP_RUNTIMEHANDLE
//
// ARRAY is used in conjunction with mdtTypeSpec tokens to construct SZARRAY types for newarr.
//
// ALLOWINSTPARAM is used in conjunction with mdtMemberRef, mdtMethodSpec
// and mdtMethodDef tokens to indicate that the caller can deal with methods
// that require instantiation parameters (at present this is shared-code
// generic methods and shared-code instance methods in generic structs).
//
// If not set (the default), then you'll get a specialized stub instead,
// which is required for LDFTN and also by ngen as it can't assume
// anything about the implementation of generic code.
//
// ENTRYPOINT is used in conjunction with mdtMemberRef, mdtMethodSpec
// and mdtMethodDef tokens to return the entry point instead of the
// method descriptor.
//
enum CORINFO_ANNOTATION
{
CORINFO_ANNOT_NONE = 0x00000000,
// These flags are used only on TypeDef/Ref/Spec tokens
CORINFO_ANNOT_ARRAY = 0x40000000,
CORINFO_ANNOT_PERMITUNINSTDEFORREF = 0x80000000,
// These flags are used only on MethodDef/MemberRef/MethodSpec tokens
CORINFO_ANNOT_ENTRYPOINT = 0x40000000,
CORINFO_ANNOT_ALLOWINSTPARAM = 0x80000000,
CORINFO_ANNOT_DISPATCH_STUBADDR = 0xC0000000,
CORINFO_ANNOT_MASK = 0xC0000000,
};
//----------------------------------------------------------------------------
// Embedding type, method and field handles (for "ldtoken" or to pass back to helpers)
// Result of calling embedGenericHandle
struct CORINFO_GENERICHANDLE_RESULT
{
CORINFO_LOOKUP lookup;
// compileTimeHandle is guaranteed to be either NULL or a handle that is usable during compile time.
// It must not be embedded in the code because it might not be valid at run-time.
CORINFO_GENERIC_HANDLE compileTimeHandle;
};
//----------------------------------------------------------------------------
// getCallInfo and CORINFO_CALL_INFO: The EE instructs the JIT about how to make a call
//
// callKind
// --------
//
// CORINFO_CALL :
// Indicates that the JIT can use getFunctionEntryPoint to make a call,
// i.e. there is nothing abnormal about the call. The JITs know what to do if they get this.
// Except in the case of constraint calls (see below), [targetMethodHandle] will hold
// the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag may be combined with nullInstanceCheck=TRUE for uses of callvirt on methods that can
// be resolved at compile-time (non-virtual, final or sealed).
//
// CORINFO_CALL_CODE_POINTER (shared generic code only) :
// Indicates that the JIT should do an indirect call to the entrypoint given by address, which may be specified
// as a runtime lookup by CORINFO_CALL_INFO::codePointerLookup.
// [targetMethodHandle] will not hold a valid value.
// This flag may be combined with nullInstanceCheck=TRUE for uses of callvirt on methods whose target method can
// be resolved at compile-time but whose instantiation can be resolved only through runtime lookup.
//
// CORINFO_VIRTUALCALL_STUB (interface calls) :
// Indicates that the EE supports "stub dispatch" and request the JIT to make a
// "stub dispatch" call (an indirect call through CORINFO_CALL_INFO::stubLookup,
// similar to CORINFO_CALL_CODE_POINTER).
// "Stub dispatch" is a specialized calling sequence (that may require use of NOPs)
// which allow the runtime to determine the call-site after the call has been dispatched.
// If the call is too complex for the JIT (e.g. because
// fetching the dispatch stub requires a runtime lookup, i.e. lookupKind.requiresRuntimeLookup
// is set) then the JIT is allowed to implement the call as if it were CORINFO_VIRTUALCALL_LDVIRTFTN
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE.
//
// CORINFO_VIRTUALCALL_LDVIRTFTN (virtual generic methods) :
// Indicates that the EE provides no way to implement the call directly and
// that the JIT should use a LDVIRTFTN sequence (as implemented by CORINFO_HELP_VIRTUAL_FUNC_PTR)
// followed by an indirect call.
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE though typically the null check will
// be implicit in the access through the instance pointer.
//
// CORINFO_VIRTUALCALL_VTABLE (regular virtual methods) :
// Indicates that the EE supports vtable dispatch and that the JIT should use getVTableOffset etc.
// to implement the call.
// [targetMethodHandle] will hold the CORINFO_METHOD_HANDLE that a call to findMethod would
// have returned.
// This flag is always accompanied by nullInstanceCheck=TRUE though typically the null check will
// be implicit in the access through the instance pointer.
// On x64 platforms the thisInSecretRegister flag might be set. If so it indicates the callsite
// should load the instance into r11 (in addition to rcx or rdx) before making the call.
//
// thisTransform and constraint calls
// ----------------------------------
//
// For evertyhing besides "constrained." calls "thisTransform" is set to
// CORINFO_NO_THIS_TRANSFORM.
//
// For "constrained." calls the EE attempts to resolve the call at compile
// time to a more specific method, or (shared generic code only) to a runtime lookup
// for a code pointer for the more specific method.
//
// In order to permit this, the "this" pointer supplied for a "constrained." call
// is a byref to an arbitrary type (see the IL spec). The "thisTransform" field
// will indicate how the JIT must transform the "this" pointer in order
// to be able to call the resolved method:
//
// CORINFO_NO_THIS_TRANSFORM --> Leave it as a byref to an unboxed value type
// CORINFO_BOX_THIS --> Box it to produce an object
// CORINFO_DEREF_THIS --> Deref the byref to get an object reference
//
// In addition, the "kind" field will be set as follows for constraint calls:
// CORINFO_CALL --> the call was resolved at compile time, and
// can be compiled like a normal call.
// CORINFO_CALL_CODE_POINTER --> the call was resolved, but the target address will be
// computed at runtime. Only returned for shared generic code.
// CORINFO_VIRTUALCALL_STUB,
// CORINFO_VIRTUALCALL_LDVIRTFTN,
// CORINFO_VIRTUALCALL_VTABLE --> usual values indicating that a virtual call must be made
enum CORINFO_CALL_KIND
{
CORINFO_CALL,
CORINFO_CALL_CODE_POINTER,
CORINFO_VIRTUALCALL_RESOLVED,
CORINFO_VIRTUALCALL_STUB,
CORINFO_VIRTUALCALL_LDVIRTFTN,
CORINFO_VIRTUALCALL_VTABLE
};
enum CORINFO_THIS_TRANSFORM
{
CORINFO_NO_THIS_TRANSFORM,
CORINFO_BOX_THIS,
CORINFO_DEREF_THIS
};
enum CORINFO_CALLINFO_FLAGS
{
CORINFO_CALLINFO_ALLOWINSTPARAM = 0x0001, // Can the compiler generate code to pass an instantiation parameters? Simple compilers should not use this flag
CORINFO_CALLINFO_CALLVIRT = 0x0002, // Is it a virtual call?
CORINFO_CALLINFO_KINDONLY = 0x0004, // This is set to only query the kind of call to perform, without getting any other information
};
struct CORINFO_CALL_INFO
{
CORINFO_CALL_KIND kind;
BOOL nullInstanceCheck;
// See above section on constraintCalls to understand when these are set to unusual values.
CORINFO_THIS_TRANSFORM thisTransform;
CORINFO_METHOD_HANDLE targetMethodHandle;
// If kind.CORINFO_VIRTUALCALL_STUB then stubLookup will be set.
// If kind.CORINFO_CALL_CODE_POINTER then entryPointLookup will be set.
// If kind.CORINFO_VIRTUALCALL_VTABLE then thisInSecretRegister will be set. (x64 only)
union
{
CORINFO_LOOKUP stubLookup;
CORINFO_LOOKUP codePointerLookup;
};
};
// Depending on different opcodes, we might allow/disallow certain types of tokens.
// This enum is used for JIT to tell EE where this token comes from.
// EE implements its policy in CheckTokenKind() method.
enum CorInfoTokenKind
{
CORINFO_TOKENKIND_Default, // token comes from other opcodes
CORINFO_TOKENKIND_Ldtoken, // token comes from CEE_LDTOKEN
CORINFO_TOKENKIND_Casting // token comes from CEE_CASTCLASS or CEE_ISINST
};
//----------------------------------------------------------------------------
// Exception handling
struct CORINFO_EH_CLAUSE
{
CORINFO_EH_CLAUSE_FLAGS Flags;
DWORD TryOffset;
DWORD TryLength;
DWORD HandlerOffset;
DWORD HandlerLength;
union
{
DWORD ClassToken; // use for type-based exception handlers
DWORD FilterOffset; // use for filter-based exception handlers (COR_ILEXCEPTION_FILTER is set)
};
};
enum CORINFO_OS
{
CORINFO_WIN9x,
CORINFO_WINNT,
CORINFO_WINCE,
CORINFO_PAL,
};
struct CORINFO_CPU
{
DWORD dwCPUType;
DWORD dwFeatures;
DWORD dwExtendedFeatures;
};
// For some highly optimized paths, the JIT must generate code that directly
// manipulates internal EE data structures. The getEEInfo() helper returns
// this structure containing the needed offsets and values.
struct CORINFO_EE_INFO
{
// Information about the InlinedCallFrame structure layout
struct InlinedCallFrameInfo
{
// Size of the Frame structure
unsigned size;
unsigned offsetOfGSCookie;
unsigned offsetOfFrameVptr;
unsigned offsetOfFrameLink;
unsigned offsetOfCallSiteSP;
unsigned offsetOfCalleeSavedRegisters;
unsigned offsetOfCalleeSavedEbp;
unsigned offsetOfCallTarget;
unsigned offsetOfReturnAddress;
}
inlinedCallFrameInfo;
// Details about NDirectMethodFrameGeneric
unsigned sizeOfNDirectFrame;
unsigned sizeOfNDirectNegSpace;
unsigned offsetOfTransitionFrameDatum;
// Offsets into the Thread structure
unsigned offsetOfThreadFrame; // offset of the current Frame
unsigned offsetOfGCState; // offset of the preemptive/cooperative state of the Thread
// Offsets into the methodtable
unsigned offsetOfEEClass;
// Offsets into the EEClass
unsigned offsetOfInterfaceTable;
// Delegate offsets
unsigned offsetOfDelegateInstance;
unsigned offsetOfDelegateFirstTarget;
// Remoting offsets
unsigned offsetOfTransparentProxyRP;
unsigned offsetOfRealProxyServer;
CORINFO_OS osType;
unsigned osMajor;
unsigned osMinor;
unsigned osBuild;
};
// This is used to indicate that a finally has been called
// "locally" by the try block
enum { LCL_FINALLY_MARK = 0xFC }; // FC = "Finally Call"
/**********************************************************************************
* The following is the internal structure of an object that the compiler knows about
* when it generates code
**********************************************************************************/
#include <pshpack4.h>
#define CORINFO_PAGE_SIZE 0x1000 // the page size on the machine
#define MAX_UNCHECKED_OFFSET_FOR_NULL_OBJECT ((32*1024)-1) // when generating JIT code
typedef void* CORINFO_MethodPtr; // a generic method pointer
struct CORINFO_Object
{
CORINFO_MethodPtr *methTable; // the vtable for the object
};
struct CORINFO_String : public CORINFO_Object
{
unsigned buffLen;
unsigned stringLen;
const wchar_t chars[1]; // actually of variable size
};
struct CORINFO_Array : public CORINFO_Object
{
unsigned length;
union
{
__int8 i1Elems[1]; // actually of variable size
unsigned __int8 u1Elems[1];
__int16 i2Elems[1];
unsigned __int16 u2Elems[1];
__int32 i4Elems[1];
unsigned __int32 u4Elems[1];
float r4Elems[1];
};
};
#include <pshpack4.h>
struct CORINFO_Array8 : public CORINFO_Object
{
unsigned length;
union
{
double r8Elems[1];
__int64 i8Elems[1];
unsigned __int64 u8Elems[1];
};
};
#include <poppack.h>
struct CORINFO_RefArray : public CORINFO_Object
{
unsigned length;
CORINFO_CLASS_HANDLE cls;
CORINFO_Object* refElems[1]; // actually of variable size;
};
struct CORINFO_RefAny
{
void * dataPtr;
CORINFO_CLASS_HANDLE type;
};
// The jit assumes the CORINFO_VARARGS_HANDLE is a pointer to a subclass of this
struct CORINFO_VarArgInfo
{
unsigned argBytes; // number of bytes the arguments take up.
// (The CORINFO_VARARGS_HANDLE counts as an arg)
};
#include <poppack.h>
/* data to optimize delegate construction */
struct DelegateCtorArgs
{
void * pMethod;
void * pArg3;
void * pArg4;
void * pArg5;
};
// use offsetof to get the offset of the fields above
#include <stddef.h> // offsetof
#ifndef offsetof
#define offsetof(s,m) ((size_t)&(((s *)0)->m))
#endif
// Guard-stack cookie for preventing against stack buffer overruns
typedef SIZE_T GSCookie;
/**********************************************************************************/
// Some compilers cannot arbitrarily allow the handler nesting level to grow
// arbitrarily during Edit'n'Continue.
// This is the maximum nesting level that a compiler needs to support for EnC
const int MAX_EnC_HANDLER_NESTING_LEVEL = 6;
/************************************************************************
* CORINFO_METHOD_HANDLE can actually refer to either a Function or a method, the
* following callbacks are legal for either functions are methods
************************************************************************/
class ICorMethodInfo
{
public:
// this function is for debugging only. It returns the method name
// and if 'moduleName' is non-null, it sets it to something that will
// says which method (a class name, or a module name)
virtual const char* __stdcall getMethodName (
CORINFO_METHOD_HANDLE ftn, /* IN */
const char **moduleName /* OUT */
) = 0;
// this function is for debugging only. It returns a value that
// is will always be the same for a given method. It is used
// to implement the 'jitRange' functionality
virtual unsigned __stdcall getMethodHash (
CORINFO_METHOD_HANDLE ftn /* IN */
) = 0;
// return flags (defined above, CORINFO_FLG_PUBLIC ...)
// The callerHnd can be either the methodBeingCompiled or the immediate
// caller of an inlined function.
virtual DWORD __stdcall getMethodAttribs (
CORINFO_METHOD_HANDLE calleeHnd, /* IN */
CORINFO_METHOD_HANDLE callerHnd /* IN */
) = 0;
// sets private JIT flags, which can be, retrieved using getAttrib.
virtual void __stdcall setMethodAttribs (
CORINFO_METHOD_HANDLE ftn, /* IN */
CorInfoMethodRuntimeFlags attribs /* IN */
) = 0;
// Given a method descriptor ftnHnd, extract signature information into sigInfo
//
// 'memberParent' is typically only set when verifying. It should be the
// result of calling getMemberParent.
virtual void __stdcall getMethodSig (
CORINFO_METHOD_HANDLE ftn, /* IN */
CORINFO_SIG_INFO *sig, /* OUT */
CORINFO_CLASS_HANDLE memberParent = NULL /* IN */
) = 0;
/*********************************************************************
* Note the following methods can only be used on functions known
* to be IL. This includes the method being compiled and any method
* that 'getMethodInfo' returns true for
*********************************************************************/
// return information about a method private to the implementation
// returns false if method is not IL, or is otherwise unavailable.
// This method is used to fetch data needed to inline functions
virtual bool __stdcall getMethodInfo (
CORINFO_METHOD_HANDLE ftn, /* IN */
CORINFO_METHOD_INFO* info /* OUT */
) = 0;
// Decides if you have any limitations for inlining. If everything's OK, it will return
// INLINE_PASS and will fill out pRestrictions with a mask of restrictions the caller of this
// function must respect. If caller passes pRestrictions = NULL, if there are any restrictions
// INLINE_FAIL will be returned
//
//
// The inlined method need not be verified
virtual CorInfoInline __stdcall canInline (
CORINFO_METHOD_HANDLE callerHnd, /* IN */
CORINFO_METHOD_HANDLE calleeHnd, /* IN */
DWORD* pRestrictions /* OUT */
) = 0;
// Returns false if the call is across assemblies thus we cannot tailcall
virtual bool __stdcall canTailCall (
CORINFO_METHOD_HANDLE callerHnd, /* IN */
CORINFO_METHOD_HANDLE calleeHnd, /* IN */
bool fIsTailPrefix /* IN */
) = 0;
// Returns false if precompiled code must ensure that
// the EE's DoPrestub function gets run before the
// code for the method is used, i.e. if it returns false
// then an indirect call must be made.
//
// Returning true does not guaratee that a direct call can be made:
// there can be other reasons why the entry point cannot be embedded.
//
virtual bool __stdcall canSkipMethodPreparation (
CORINFO_METHOD_HANDLE callerHnd, /* IN */
CORINFO_METHOD_HANDLE calleeHnd, /* IN */
bool fCheckCode, /* IN */
CorInfoIndirectCallReason *pReason = NULL,
CORINFO_ACCESS_FLAGS accessFlags = CORINFO_ACCESS_ANY) = 0;
// Returns true if a direct call can be made via the method entry point
//
virtual bool __stdcall canCallDirectViaEntryPointThunk (
CORINFO_METHOD_HANDLE calleeHnd, /* IN */
void ** pEntryPoint /* OUT */
) = 0;
// get individual exception handler
virtual void __stdcall getEHinfo(
CORINFO_METHOD_HANDLE ftn, /* IN */
unsigned EHnumber, /* IN */
CORINFO_EH_CLAUSE* clause /* OUT */
) = 0;
// return class it belongs to
virtual CORINFO_CLASS_HANDLE __stdcall getMethodClass (
CORINFO_METHOD_HANDLE method
) = 0;
// return module it belongs to
virtual CORINFO_MODULE_HANDLE __stdcall getMethodModule (
CORINFO_METHOD_HANDLE method
) = 0;
// This function returns the offset of the specified method in the
// vtable of it's owning class or interface.
virtual unsigned __stdcall getMethodVTableOffset (
CORINFO_METHOD_HANDLE method
) = 0;
// If a method's attributes have (getMethodAttribs) CORINFO_FLG_INTRINSIC set,
// getIntrinsicID() returns the intrinsic ID.
virtual CorInfoIntrinsics __stdcall getIntrinsicID(
CORINFO_METHOD_HANDLE method
) = 0;
// return the unmanaged calling convention for a PInvoke
virtual CorInfoUnmanagedCallConv __stdcall getUnmanagedCallConv(
CORINFO_METHOD_HANDLE method
) = 0;
// return if any marshaling is required for PInvoke methods. Note that
// method == 0 => calli. The call site sig is only needed for the varargs or calli case
virtual BOOL __stdcall pInvokeMarshalingRequired(
CORINFO_METHOD_HANDLE method,
CORINFO_SIG_INFO* callSiteSig
) = 0;
// Check Visibility rules.
// For Protected (family access) members, type of the instance is also
// considered when checking visibility rules.
virtual BOOL __stdcall canAccessMethod(
CORINFO_METHOD_HANDLE context,
CORINFO_CLASS_HANDLE parent,
CORINFO_METHOD_HANDLE target,
CORINFO_CLASS_HANDLE instance
) = 0;
// Check constraints on method type arguments (only).
// The parent class should be checked separately using satisfiesClassConstraints(parent).
virtual BOOL __stdcall satisfiesMethodConstraints(
CORINFO_CLASS_HANDLE parent, // the exact parent of the method
CORINFO_METHOD_HANDLE method
) = 0;
// Given a delegate target class, a target method parent class, a target method,
// a delegate class, a scope, the target method ref, and the delegate constructor member ref
// check if the method signature is compatible with the Invoke method of the delegate
// (under the typical instantiation of any free type variables in the memberref signatures).
// NB: arguments 2-4 could be inferred from 5-7, but are assumed to be available, and thus passed in for efficiency.
virtual BOOL __stdcall isCompatibleDelegate(
CORINFO_CLASS_HANDLE objCls, /* type of the delegate target, if any */
CORINFO_CLASS_HANDLE methodParentCls, /* exact parent of the target method, if any */
CORINFO_METHOD_HANDLE method, /* (representative) target method, if any */
CORINFO_CLASS_HANDLE delegateCls, /* exact type of the delegate */
CORINFO_MODULE_HANDLE moduleHnd, /* scope of the following refs */
unsigned methodMemberRef, /* memberref of the target method */
unsigned delegateConstructorMemberRef /* memberref of the delegate constructor */
) = 0;
// Indicates if the method is an instance of the generic
// method that passes (or has passed) verification
virtual CorInfoInstantiationVerification __stdcall isInstantiationOfVerifiedGeneric (
CORINFO_METHOD_HANDLE method /* IN */
) = 0;
// Loads the constraints on a typical method definition, detecting cycles;
// for use in verification.
virtual void __stdcall initConstraintsForVerification(
CORINFO_METHOD_HANDLE method, /* IN */
BOOL *pfHasCircularClassConstraints, /* OUT */
BOOL *pfHasCircularMethodConstraint /* OUT */
) = 0;
// Returns enum whether the method does not require verification
// Also see ICorModuleInfo::canSkipVerification
virtual CorInfoCanSkipVerificationResult __stdcall canSkipMethodVerification (
CORINFO_METHOD_HANDLE ftnHandle, /* IN */
BOOL fQuickCheckOnly
) = 0;
// Determines whether a callout is allowed.
virtual CorInfoIsCallAllowedResult __stdcall isCallAllowed (
CORINFO_METHOD_HANDLE callerHnd, // IN
CORINFO_METHOD_HANDLE calleeHnd, // IN
CORINFO_CALL_ALLOWED_INFO * CallAllowedInfo // OUT
) = 0;
// load and restore the method
virtual void __stdcall methodMustBeLoadedBeforeCodeIsRun(
CORINFO_METHOD_HANDLE method
) = 0;
virtual CORINFO_METHOD_HANDLE __stdcall mapMethodDeclToMethodImpl(
CORINFO_METHOD_HANDLE method
) = 0;
// Returns the global cookie for the /GS unsafe buffer checks
// The cookie might be a constant value (JIT), or a handle to memory location (Ngen)
virtual void __stdcall getGSCookie(
GSCookie * pCookieVal, // OUT
GSCookie ** ppCookieVal // OUT
) = 0;
};
/**********************************************************************************/
class ICorModuleInfo
{
public:
// Given a type token metaTOK, use context to instantiate any type variables and return a type handle
// The context parameter is also used to do access checks.
virtual CORINFO_CLASS_HANDLE __stdcall findClass (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned metaTOK, /* IN */
CORINFO_CONTEXT_HANDLE context, /* IN */
CorInfoTokenKind tokenKind = CORINFO_TOKENKIND_Default /* IN */
) = 0;
// Given a field token metaTOK, use context to instantiate any type variables in its *parent* type and return a field handle
// The context parameter is also used to do access checks.
virtual CORINFO_FIELD_HANDLE __stdcall findField (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned metaTOK, /* IN */
CORINFO_CONTEXT_HANDLE context /* IN */
) = 0;
// Given a method token metaTOK, use context to instantiate any type variables in its *parent* type and return a method handle
// This looks up a function by token (what the IL CALLVIRT, CALLSTATIC instructions use)
// The context parameter is also used to do access checks.
// If metaTOK is combined with the flag CORINFO_ANNOT_ALLOWINSTPARAM and it refers to a generic method or an instance method in a generic struct,
// then the method handle returned might be for shared code which expects an extra parameter providing extra instantiation information.
// Otherwise (the default), a specialized stub method is returned that doesn't take this parameter
virtual CORINFO_METHOD_HANDLE __stdcall findMethod (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned metaTOK, /* IN */
CORINFO_CONTEXT_HANDLE context /* IN */
) = 0;
// Given a field or method token metaTOK return its parent token
virtual unsigned __stdcall getMemberParent(CORINFO_MODULE_HANDLE scopeHnd, unsigned metaTOK) = 0;
// Signature information about the call sig
virtual void __stdcall findSig (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned sigTOK, /* IN */
CORINFO_METHOD_HANDLE context, /* IN */
CORINFO_SIG_INFO *sig /* OUT */
) = 0;
// for Varargs, the signature at the call site may differ from
// the signature at the definition. Thus we need a way of
// fetching the call site information
virtual void __stdcall findCallSiteSig (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned methTOK, /* IN */
CORINFO_METHOD_HANDLE context, /* IN */
CORINFO_SIG_INFO *sig /* OUT */
) = 0;
virtual CORINFO_CLASS_HANDLE __stdcall getTokenTypeAsHandle (
CORINFO_MODULE_HANDLE scopeHnd,
unsigned metaTOK) = 0;
virtual size_t __stdcall findNameOfToken (
CORINFO_MODULE_HANDLE module, /* IN */
mdToken metaTOK, /* IN */
__out_ecount (FQNameCapacity) char * szFQName, /* OUT */
size_t FQNameCapacity /* IN */
) = 0;
// Returns true if the module does not require verification
//
// If fQuickCheckOnlyWithoutCommit=TRUE, the function only checks that the
// module does not currently require verification in the current AppDomain.
// This decision could change in the future, and so should not be cached.
// If it is cached, it should only be used as a hint.
// This is only used by ngen for calculating certain hints.
//
// Returns enum whether the module does not require verification
// Also see ICorMethodInfo::canSkipMethodVerification();
virtual CorInfoCanSkipVerificationResult __stdcall canSkipVerification (
CORINFO_MODULE_HANDLE module, /* IN */
BOOL fQuickCheckOnlyWithoutCommit = FALSE /* IN */
) = 0;
// Checks if the given metadata token is valid
virtual BOOL __stdcall isValidToken (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned metaTOK /* IN */
) = 0;
// Checks if the given metadata token is valid StringRef
virtual BOOL __stdcall isValidStringRef (
CORINFO_MODULE_HANDLE module, /* IN */
unsigned metaTOK /* IN */
) = 0;
};
/**********************************************************************************/
class ICorClassInfo
{
public:
// If the value class 'cls' is isomorphic to a primitive type it will
// return that type, otherwise it will return CORINFO_TYPE_VALUECLASS
virtual CorInfoType __stdcall asCorInfoType (
CORINFO_CLASS_HANDLE cls
) = 0;
// for completeness
virtual const char* __stdcall getClassName (
CORINFO_CLASS_HANDLE cls
) = 0;
// Append a (possibly truncated) representation of the type cls to the preallocated buffer ppBuf of length pnBufLen
// If fNamespace=TRUE, include the namespace/enclosing classes
// If fFullInst=TRUE (regardless of fNamespace and fAssembly), include namespace and assembly for any type parameters
// If fAssembly=TRUE, suffix with a comma and the full assembly qualification
// return size of representation
virtual int __stdcall appendClassName(
WCHAR** ppBuf, int* pnBufLen,
CORINFO_CLASS_HANDLE cls,
BOOL fNamespace,
BOOL fFullInst,
BOOL fAssembly
) = 0;
// If this method returns true, JIT will do optimization to inline the check for
// GetClassFromHandle(handle) == obj.GetType()
virtual BOOL __stdcall canInlineTypeCheckWithObjectVTable(CORINFO_CLASS_HANDLE cls) = 0;
// return flags (defined above, CORINFO_FLG_PUBLIC ...)
//
// The "methodBeingCompiled" parameter is used to determine
// domain-neutrality of the code being generated, for the CORINFO_FLG_NEEDS_INIT
// and CORINFO_FLG_INITIALIZED flags. It thus is really used
// to represent a compilation scope. If you are inling
// methods, then methodBeingCompiled should be the originating
// method being compiled, not the nested method that refers to "cls".
virtual DWORD __stdcall getClassAttribs (
CORINFO_CLASS_HANDLE cls,
CORINFO_METHOD_HANDLE methodBeingCompiledHnd
) = 0;
virtual CORINFO_MODULE_HANDLE __stdcall getClassModule (
CORINFO_CLASS_HANDLE cls
) = 0;
virtual CORINFO_MODULE_HANDLE __stdcall getClassModuleForStatics (
CORINFO_CLASS_HANDLE cls
) = 0;
// get the class representing the single dimensional array for the
// element type represented by clsHnd
virtual CORINFO_CLASS_HANDLE __stdcall getSDArrayForClass (
CORINFO_CLASS_HANDLE clsHnd
) = 0 ;
// return the number of bytes needed by an instance of the class
virtual unsigned __stdcall getClassSize (
CORINFO_CLASS_HANDLE cls
) = 0;
virtual unsigned __stdcall getClassAlignmentRequirement (
CORINFO_CLASS_HANDLE cls
) = 0;
// This is only called for Value classes. It returns a boolean array
// in representing of 'cls' from a GC perspective. The class is
// assumed to be an array of machine words
// (of length // getClassSize(cls) / sizeof(void*)),
// 'gcPtrs' is a poitner to an array of BYTEs of this length.
// getClassGClayout fills in this array so that gcPtrs[i] is set
// to one of the CorInfoGCType values which is the GC type of
// the i-th machine word of an object of type 'cls'
// returns the number of GC pointers in the array
virtual unsigned __stdcall getClassGClayout (
CORINFO_CLASS_HANDLE cls, /* IN */
BYTE *gcPtrs /* OUT */
) = 0;
// returns the number of instance fields in a class
virtual unsigned __stdcall getClassNumInstanceFields (
CORINFO_CLASS_HANDLE cls /* IN */
) = 0;
virtual CORINFO_FIELD_HANDLE __stdcall getFieldInClass(
CORINFO_CLASS_HANDLE clsHnd,
INT num
) = 0;
virtual INT __stdcall getClassCustomAttribute(
CORINFO_CLASS_HANDLE clsHnd,
LPCSTR attrib,
const BYTE** ppVal
) = 0;
virtual mdMethodDef __stdcall getMethodDefFromMethod(
CORINFO_METHOD_HANDLE hMethod
) = 0;
virtual BOOL __stdcall checkMethodModifier(
CORINFO_METHOD_HANDLE hMethod,
LPCSTR modifier,
BOOL fOptional
) = 0;
// returns the "NEW" helper optimized for "newCls."
virtual CorInfoHelpFunc __stdcall getNewHelper(
CORINFO_CLASS_HANDLE newCls,
CORINFO_METHOD_HANDLE context,
unsigned classToken,
CORINFO_MODULE_HANDLE tokenContext
) = 0;
// returns the newArr (1-Dim array) helper optimized for "arrayCls."
virtual CorInfoHelpFunc __stdcall getNewArrHelper(
CORINFO_CLASS_HANDLE arrayCls,
CORINFO_METHOD_HANDLE context
) = 0;
// returns the newMdArr (multi-Dim array) helper optimized for "arrayCtorMethod"
virtual CorInfoHelpFunc __stdcall getNewMDArrHelper(
CORINFO_CLASS_HANDLE arrayCls,
CORINFO_METHOD_HANDLE arrayCtorMethod,
CORINFO_METHOD_HANDLE context
) = 0;
// returns the "IsInstanceOf" helper optimized for "IsInstCls."
virtual CorInfoHelpFunc __stdcall getIsInstanceOfHelper(
CORINFO_MODULE_HANDLE scopeHnd,
unsigned metaTOK,
CORINFO_CONTEXT_HANDLE context) = 0;
// returns the "ChkCast" helper optimized for "IsInstCls."
virtual CorInfoHelpFunc __stdcall getChkCastHelper(
CORINFO_MODULE_HANDLE scopeHnd,
unsigned metaTOK,
CORINFO_CONTEXT_HANDLE context) = 0;
virtual CorInfoHelpFunc __stdcall getSharedStaticBaseHelper(
CORINFO_FIELD_HANDLE fldHnd,
BOOL runtimeLookup = FALSE
) = 0;
virtual CorInfoHelpFunc __stdcall getSharedCCtorHelper(
CORINFO_CLASS_HANDLE clsHnd
) = 0;
virtual CorInfoHelpFunc __stdcall getSecurityHelper(
CORINFO_METHOD_HANDLE ftn,
BOOL fEnter // TRUE = prolog, FALSE = epilog
) = 0;
// This is not pretty. Boxing nullable<T> actually returns
// a boxed<T> not a boxed Nullable<T>. This call allows the verifier
// to call back to the EE on the 'box' instruction and get the transformed
// type to use for verification.
virtual CORINFO_CLASS_HANDLE getTypeForBox(
CORINFO_CLASS_HANDLE cls
) = 0;
// returns the correct box helper for a particular class. Note
// that if this returns CORINFO_HELP_BOX, the JIT can assume
// 'standard' boxing (allocate object and copy), and optimize
virtual CorInfoHelpFunc __stdcall getBoxHelper(
CORINFO_CLASS_HANDLE cls
) = 0;
// returns the unbox helper. If 'helperCopies' points to a true
// value it means the JIT is requesting a helper that unboxes the
// value into a particular location and thus has the signature
// void unboxHelper(void* dest, CORINFO_CLASS_HANDLE cls, Object* obj)
// Otherwise (it is null or points at a FALSE value) it is requesting
// a helper that returns a poitner to the unboxed data
// void* unboxHelper(CORINFO_CLASS_HANDLE cls, Object* obj)
// The EE has the option of NOT returning the copy style helper
// (But must be able to always honor the non-copy style helper)
// The EE set 'helperCopies' on return to indicate what kind of
// helper has been created.
virtual CorInfoHelpFunc __stdcall getUnBoxHelper(
CORINFO_CLASS_HANDLE cls,
BOOL* helperCopies = NULL
) = 0;
virtual const char* __stdcall getHelperName(
CorInfoHelpFunc
) = 0;
// This function tries to initialize the class (run the class constructor).
// this function can return false, which means that the JIT must
// insert helper calls before accessing class members.
//
// This should probably be renamed to something like "ensureClassIsInitedBeforeCodeIsRun"
// but that doesn't capture the fact that the function returns FALSE if a slow path
// is needed to ensure the initialization semantics for the class.
//
// The methodBeingCompiledHnd is used to determine if
virtual BOOL __stdcall initClass(
CORINFO_CLASS_HANDLE cls,
CORINFO_METHOD_HANDLE methodBeingCompiledHnd,
BOOL speculative = FALSE, // TRUE means don't actually run it
BOOL *pfNeedsInitFixup = NULL // Set to TRUE if it is necessary to init the class by fixup in prejit code
) = 0;
// This used to be called "loadClass". This records the fact
// that the class must be loaded (including restored if necessary) before we execute the
// code that we are currently generating. When jitting code
// the function loads the class immediately. When zapping code
// the zapper will if necessary use the call to record the fact that we have
// to do a fixup/restore before running the method currently being generated.
//
// This is typically used to ensure value types are loaded before zapped
// code that manipulates them is executed, so that the GC can access information
// about those value types.
virtual void __stdcall classMustBeLoadedBeforeCodeIsRun(
CORINFO_CLASS_HANDLE cls
) = 0;
// returns the class handle for the special builtin classes
virtual CORINFO_CLASS_HANDLE __stdcall getBuiltinClass (
CorInfoClassId classId
) = 0;
// "System.Int32" ==> CORINFO_TYPE_INT..
virtual CorInfoType __stdcall getTypeForPrimitiveValueClass(
CORINFO_CLASS_HANDLE cls
) = 0;
// TRUE if child is a subtype of parent
// if parent is an interface, then does child implement / extend parent
virtual BOOL __stdcall canCast(
CORINFO_CLASS_HANDLE child, // subtype (extends parent)
CORINFO_CLASS_HANDLE parent // base type
) = 0;
// returns is the intersection of cls1 and cls2.
virtual CORINFO_CLASS_HANDLE __stdcall mergeClasses(
CORINFO_CLASS_HANDLE cls1,
CORINFO_CLASS_HANDLE cls2
) = 0;
// Given a class handle, returns the Parent type.
// For COMObjectType, it returns Class Handle of System.Object.
// Returns 0 if System.Object is passed in.
virtual CORINFO_CLASS_HANDLE __stdcall getParentType (
CORINFO_CLASS_HANDLE cls
) = 0;
// Returns the CorInfoType of the "child type". If the child type is
// not a primitive type, *clsRet will be set.
// Given an Array of Type Foo, returns Foo.
// Given BYREF Foo, returns Foo
virtual CorInfoType __stdcall getChildType (
CORINFO_CLASS_HANDLE clsHnd,
CORINFO_CLASS_HANDLE *clsRet
) = 0;
// Check Visibility rules.
virtual BOOL __stdcall canAccessType(
CORINFO_METHOD_HANDLE context,
CORINFO_CLASS_HANDLE target
) = 0;
// Check constraints on type arguments of this class and parent classes
virtual BOOL __stdcall satisfiesClassConstraints(
CORINFO_CLASS_HANDLE cls
) = 0;
// Check if this is a single dimensional array type
virtual BOOL __stdcall isSDArray(
CORINFO_CLASS_HANDLE cls
) = 0;
// Get the numbmer of dimensions in an array
virtual unsigned __stdcall getArrayRank(
CORINFO_CLASS_HANDLE cls
) = 0;
// Get static field data for an array
virtual void * __stdcall getArrayInitializationData(
CORINFO_FIELD_HANDLE field,
DWORD size
) = 0;
};
/**********************************************************************************/
class ICorFieldInfo
{
public:
// this function is for debugging only. It returns the field name
// and if 'moduleName' is non-null, it sets it to something that will
// says which method (a class name, or a module name)
virtual const char* __stdcall getFieldName (
CORINFO_FIELD_HANDLE ftn, /* IN */
const char **moduleName /* OUT */
) = 0;
// return flags (defined above, CORINFO_FLG_PUBLIC ...)
virtual DWORD __stdcall getFieldAttribs (
CORINFO_FIELD_HANDLE field,
CORINFO_METHOD_HANDLE context,
CORINFO_ACCESS_FLAGS flags = CORINFO_ACCESS_ANY
) = 0;
// return class it belongs to
virtual CORINFO_CLASS_HANDLE __stdcall getFieldClass (
CORINFO_FIELD_HANDLE field
) = 0;
// Return the field's type, if it is CORINFO_TYPE_VALUECLASS 'structType' is set
// the field's value class (if 'structType' == 0, then don't bother
// the structure info).
//
// 'memberParent' is typically only set when verifying. It should be the
// result of calling getMemberParent.
virtual CorInfoType __stdcall getFieldType(
CORINFO_FIELD_HANDLE field,
CORINFO_CLASS_HANDLE *structType,
CORINFO_CLASS_HANDLE memberParent = NULL /* IN */
) = 0;
// returns the field's compilation category
virtual CorInfoFieldCategory __stdcall getFieldCategory (
CORINFO_FIELD_HANDLE field
) = 0;
// returns the field's compilation category
virtual CorInfoHelpFunc __stdcall getFieldHelper(
CORINFO_FIELD_HANDLE field,
enum CorInfoFieldAccess kind // Get, Set, Address
) = 0;
// return the data member's instance offset
virtual unsigned __stdcall getFieldOffset (
CORINFO_FIELD_HANDLE field
) = 0;
// Check Visibility rules.
// For Protected (family access) members, type of the instance is also
// considered when checking visibility rules.
virtual BOOL __stdcall canAccessField(
CORINFO_METHOD_HANDLE context,
CORINFO_CLASS_HANDLE parent,
CORINFO_FIELD_HANDLE target,
CORINFO_CLASS_HANDLE instance
) = 0;
};
/*********************************************************************************/
class ICorDebugInfo
{
public:
/*----------------------------- Boundary-info ---------------------------*/
enum MappingTypes
{
NO_MAPPING = -1,
PROLOG = -2,
EPILOG = -3,
MAX_MAPPING_VALUE = -3 // Sentinal value. This should be set to the largest magnitude value in the enum
// so that the compression routines know the enum's range.
};
enum BoundaryTypes
{
NO_BOUNDARIES = 0x00, // No implicit boundaries
STACK_EMPTY_BOUNDARIES = 0x01, // Boundary whenever the IL evaluation stack is empty
NOP_BOUNDARIES = 0x02, // Before every CEE_NOP instruction
CALL_SITE_BOUNDARIES = 0x04, // Before every CEE_CALL, CEE_CALLVIRT, etc instruction
// Set of boundaries that debugger should always reasonably ask the JIT for.
DEFAULT_BOUNDARIES = STACK_EMPTY_BOUNDARIES | NOP_BOUNDARIES | CALL_SITE_BOUNDARIES
};
// Note that SourceTypes can be OR'd together - it's possible that
// a sequence point will also be a stack_empty point, and/or a call site.
// The debugger will check to see if a boundary offset's source field &
// SEQUENCE_POINT is true to determine if the boundary is a sequence point.
enum SourceTypes
{
SOURCE_TYPE_INVALID = 0x00, // To indicate that nothing else applies
SEQUENCE_POINT = 0x01, // The debugger asked for it.
STACK_EMPTY = 0x02, // The stack is empty here
CALL_SITE = 0x04, // This is a call site.
NATIVE_END_OFFSET_UNKNOWN = 0x08 // Indicates a epilog endpoint
};
struct OffsetMapping
{
DWORD nativeOffset;
DWORD ilOffset;
SourceTypes source; // The debugger needs this so that
// we don't put Edit and Continue breakpoints where
// the stack isn't empty. We can put regular breakpoints
// there, though, so we need a way to discriminate
// between offsets.
};
// Query the EE to find out where interesting break points
// in the code are. The native compiler will ensure that these places
// have a corresponding break point in native code.
//
// Note that unless CORJIT_FLG_DEBUG_CODE is specified, this function will
// be used only as a hint and the native compiler should not change its
// code generation.
virtual void __stdcall getBoundaries(
CORINFO_METHOD_HANDLE ftn, // [IN] method of interest
unsigned int *cILOffsets, // [OUT] size of pILOffsets
DWORD **pILOffsets, // [OUT] IL offsets of interest
// jit MUST free with freeArray!
BoundaryTypes *implictBoundaries // [OUT] tell jit, all boundries of this type
) = 0;
// Report back the mapping from IL to native code,
// this map should include all boundaries that 'getBoundaries'
// reported as interesting to the debugger.
// Note that debugger (and profiler) is assuming that all of the
// offsets form a contiguous block of memory, and that the
// OffsetMapping is sorted in order of increasing native offset.
virtual void __stdcall setBoundaries(
CORINFO_METHOD_HANDLE ftn, // [IN] method of interest
ULONG32 cMap, // [IN] size of pMap
OffsetMapping *pMap // [IN] map including all points of interest.
// jit allocated with allocateArray, EE frees
) = 0;
/*------------------------------ Var-info -------------------------------*/
enum RegNum
{
#ifdef _X86_
REGNUM_EAX,
REGNUM_ECX,
REGNUM_EDX,
REGNUM_EBX,
REGNUM_ESP,
REGNUM_EBP,
REGNUM_ESI,
REGNUM_EDI,
#elif _PPC_
REGNUM_R1,
REGNUM_R30,
REGNUM_R3,
REGNUM_R4,
REGNUM_R5,
REGNUM_R6,
REGNUM_R7,
REGNUM_R8,
REGNUM_R9,
REGNUM_R10,
#else
PORTABILITY_WARNING("Register numbers not defined on this platform")
#endif
REGNUM_COUNT,
REGNUM_AMBIENT_SP, // ambient SP support. Ambient SP is the original SP in the non-BP based frame.
// Ambient SP should not change even if there are push/pop operations in the method.
#ifdef _X86_
REGNUM_FP = REGNUM_EBP,
REGNUM_SP = REGNUM_ESP,
#elif _PPC_
REGNUM_FP = REGNUM_R30,
REGNUM_SP = REGNUM_R1,
#else
// RegNum values should be properly defined for this platform
REGNUM_FP = 0,
REGNUM_SP = 1,
#endif
};
// VarLoc describes the location of a native variable. Note that currently, VLT_REG_BYREF and VLT_STK_BYREF
// are only used for value types on X64.
enum VarLocType
{
VLT_REG, // variable is in a register
VLT_REG_BYREF, // address of the variable is in a register
VLT_REG_FP, // variable is in an fp register
VLT_STK, // variable is on the stack (memory addressed relative to the frame-pointer)
VLT_STK_BYREF, // address of the variable is on the stack (memory addressed relative to the frame-pointer)
VLT_REG_REG, // variable lives in two registers
VLT_REG_STK, // variable lives partly in a register and partly on the stack
VLT_STK_REG, // reverse of VLT_REG_STK
VLT_STK2, // variable lives in two slots on the stack
VLT_FPSTK, // variable lives on the floating-point stack
VLT_FIXED_VA, // variable is a fixed argument in a varargs function (relative to VARARGS_HANDLE)
VLT_COUNT,
VLT_INVALID
};
struct VarLoc
{
VarLocType vlType;
union
{
// VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
// eg. EAX
// VLT_REG_BYREF -- the specified register contains the address of the variable
// eg. [EAX]
struct
{
RegNum vlrReg;
} vlReg;
// VLT_STK -- Any 32 bit value which is on the stack
// eg. [ESP+0x20], or [EBP-0x28]
// VLT_STK_BYREF -- the specified stack location contains the address of the variable
// eg. mov EAX, [ESP+0x20]; [EAX]
struct
{
RegNum vlsBaseReg;
signed vlsOffset;
} vlStk;
// VLT_REG_REG -- TYP_LONG with both DWords enregistred
// eg. RBM_EAXEDX
struct
{
RegNum vlrrReg1;
RegNum vlrrReg2;
} vlRegReg;
// VLT_REG_STK -- Partly enregistered TYP_LONG
// eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
struct
{
RegNum vlrsReg;
struct
{
RegNum vlrssBaseReg;
signed vlrssOffset;
} vlrsStk;
} vlRegStk;
// VLT_STK_REG -- Partly enregistered TYP_LONG
// eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
struct
{
struct
{
RegNum vlsrsBaseReg;
signed vlsrsOffset;
} vlsrStk;
RegNum vlsrReg;
} vlStkReg;
// VLT_STK2 -- Any 64 bit value which is on the stack,
// in 2 successsive DWords.
// eg 2 DWords at [ESP+0x10]
struct
{
RegNum vls2BaseReg;
signed vls2Offset;
} vlStk2;
// VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
// eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk")
struct
{
unsigned vlfReg;
} vlFPstk;
// VLT_FIXED_VA -- fixed argument of a varargs function.
// The argument location depends on the size of the variable
// arguments (...). Inspecting the VARARGS_HANDLE indicates the
// location of the first arg. This argument can then be accessed
// relative to the position of the first arg
struct
{
unsigned vlfvOffset;
} vlFixedVarArg;
// VLT_MEMORY
struct
{
void *rpValue; // pointer to the in-process
// location of the value.
} vlMemory;
};
};
// This is used to report implicit/hidden arguments
enum
{
VARARGS_HND_ILNUM = -1, // Value for the CORINFO_VARARGS_HANDLE varNumber
RETBUF_ILNUM = -2, // Pointer to the return-buffer
TYPECTXT_ILNUM = -3, // ParamTypeArg for CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG
UNKNOWN_ILNUM = -4, // Unknown variable
MAX_ILNUM = -4 // Sentinal value. This should be set to the largest magnitude value in th enum
// so that the compression routines know the enum's range.
};
struct ILVarInfo
{
DWORD startOffset;
DWORD endOffset;
DWORD varNumber;
};
struct NativeVarInfo
{
DWORD startOffset;
DWORD endOffset;
DWORD varNumber;
VarLoc loc;
};
// Query the EE to find out the scope of local varables.
// normally the JIT would trash variables after last use, but
// under debugging, the JIT needs to keep them live over their
// entire scope so that they can be inspected.
//
// Note that unless CORJIT_FLG_DEBUG_CODE is specified, this function will
// be used only as a hint and the native compiler should not change its
// code generation.
virtual void __stdcall getVars(
CORINFO_METHOD_HANDLE ftn, // [IN] method of interest
ULONG32 *cVars, // [OUT] size of 'vars'
ILVarInfo **vars, // [OUT] scopes of variables of interest
// jit MUST free with freeArray!
bool *extendOthers // [OUT] it TRUE, then assume the scope
// of unmentioned vars is entire method
) = 0;
// Report back to the EE the location of every variable.
// note that the JIT might split lifetimes into different
// locations etc.
virtual void __stdcall setVars(
CORINFO_METHOD_HANDLE ftn, // [IN] method of interest
ULONG32 cVars, // [IN] size of 'vars'
NativeVarInfo *vars // [IN] map telling where local vars are stored at what points
// jit allocated with allocateArray, EE frees
) = 0;
/*-------------------------- Misc ---------------------------------------*/
// Used to allocate memory that needs to handed to the EE.
// For eg, use this to allocated memory for reporting debug info,
// which will be handed to the EE by setVars() and setBoundaries()
virtual void * __stdcall allocateArray(
ULONG cBytes
) = 0;
// JitCompiler will free arrays passed by the EE using this
// For eg, The EE returns memory in getVars() and getBoundaries()
// to the JitCompiler, which the JitCompiler should release using
// freeArray()
virtual void __stdcall freeArray(
void *array
) = 0;
};
/*****************************************************************************/
class ICorArgInfo
{
public:
// advance the pointer to the argument list.
// a ptr of 0, is special and always means the first argument
virtual CORINFO_ARG_LIST_HANDLE __stdcall getArgNext (
CORINFO_ARG_LIST_HANDLE args /* IN */
) = 0;
// Get the type of a particular argument
// CORINFO_TYPE_UNDEF is returned when there are no more arguments
// If the type returned is a primitive type (or an enum) *vcTypeRet set to NULL
// otherwise it is set to the TypeHandle associted with the type
// Enumerations will always look their underlying type (probably should fix this)
// Otherwise vcTypeRet is the type as would be seen by the IL,
// The return value is the type that is used for calling convention purposes
// (Thus if the EE wants a value class to be passed like an int, then it will
// return CORINFO_TYPE_INT
virtual CorInfoTypeWithMod __stdcall getArgType (
CORINFO_SIG_INFO* sig, /* IN */
CORINFO_ARG_LIST_HANDLE args, /* IN */
CORINFO_CLASS_HANDLE *vcTypeRet /* OUT */
) = 0;
// If the Arg is a CORINFO_TYPE_CLASS fetch the class handle associated with it
virtual CORINFO_CLASS_HANDLE __stdcall getArgClass (
CORINFO_SIG_INFO* sig, /* IN */
CORINFO_ARG_LIST_HANDLE args /* IN */
) = 0;
};
class ICorLinkInfo
{
public:
// Called when an absolute or relative pointer is embedded in the code
// stream. A relocation is recorded if we are pre-jitting.
virtual void __stdcall recordRelocation(
void *location, /* IN */
WORD fRelocType /* IN */
) = 0;
};
/*****************************************************************************
* ICorErrorInfo contains methods to deal with SEH exceptions being thrown
* from the corinfo interface. These methods may be called when an exception
* with code EXCEPTION_COMPLUS is caught.
*
*
*****************************************************************************/
class ICorErrorInfo
{
public:
// Returns the HRESULT of the current exception
virtual HRESULT __stdcall GetErrorHRESULT(
struct _EXCEPTION_POINTERS *pExceptionPointers
) = 0;
// Returns the class of the current exception
virtual CORINFO_CLASS_HANDLE __stdcall GetErrorClass() = 0;
// Fetches the message of the current exception
// Returns the size of the message (including terminating null). This can be
// greater than bufferLength if the buffer is insufficient.
virtual ULONG __stdcall GetErrorMessage(
LPWSTR buffer,
ULONG bufferLength
) = 0;
// returns EXCEPTION_EXECUTE_HANDLER if it is OK for the compile to handle the
// exception, abort some work (like the inlining) and continue compilation
// returns EXCEPTION_CONTINUE_SEARCH if exception must always be handled by the EE
// things like ThreadStoppedException ...
// returns EXCEPTION_CONTINUE_EXECUTION if exception is fixed up by the EE
virtual int __stdcall FilterException(
struct _EXCEPTION_POINTERS *pExceptionPointers
) = 0;
};
/*****************************************************************************
* ICorStaticInfo contains EE interface methods which return values that are
* constant from invocation to invocation. Thus they may be embedded in
* persisted information like statically generated code. (This is of course
* assuming that all code versions are identical each time.)
*****************************************************************************/
class ICorStaticInfo : public virtual ICorMethodInfo, public virtual ICorModuleInfo,
public virtual ICorClassInfo, public virtual ICorFieldInfo,
public virtual ICorDebugInfo, public virtual ICorArgInfo,
public virtual ICorLinkInfo, public virtual ICorErrorInfo
{
public:
// Return details about EE internal data structures
virtual void __stdcall getEEInfo(
CORINFO_EE_INFO *pEEInfoOut
) = 0;
};
/*****************************************************************************
* ICorDynamicInfo contains EE interface methods which return values that may
* change from invocation to invocation. They cannot be embedded in persisted
* data; they must be requeried each time the EE is run.
*****************************************************************************/
class ICorDynamicInfo : public virtual ICorStaticInfo
{
public:
//
// These methods return values to the JIT which are not constant
// from session to session.
//
// These methods take an extra parameter : void **ppIndirection.
// If a JIT supports generation of prejit code (install-o-jit), it
// must pass a non-null value for this parameter, and check the
// resulting value. If *ppIndirection is NULL, code should be
// generated normally. If non-null, then the value of
// *ppIndirection is an address in the cookie table, and the code
// generator needs to generate an indirection through the table to
// get the resulting value. In this case, the return result of the
// function must NOT be directly embedded in the generated code.
//
// Note that if a JIT does not support prejit code generation, it
// may ignore the extra parameter & pass the default of NULL - the
// prejit ICorDynamicInfo implementation will see this & generate
// an error if the jitter is used in a prejit scenario.
//
// Return details about EE internal data structures
virtual DWORD __stdcall getThreadTLSIndex(
void **ppIndirection = NULL
) = 0;
virtual const void * __stdcall getInlinedCallFrameVptr(
void **ppIndirection = NULL
) = 0;
virtual LONG * __stdcall getAddrOfCaptureThreadGlobal(
void **ppIndirection = NULL
) = 0;
virtual SIZE_T* __stdcall getAddrModuleDomainID(CORINFO_MODULE_HANDLE module) = 0;
// return the native entry point to an EE helper (see CorInfoHelpFunc)
virtual void* __stdcall getHelperFtn (
CorInfoHelpFunc ftnNum,
void **ppIndirection = NULL,
InfoAccessModule *pAccessModule = NULL
) = 0;
// return a callable address of the function (native code). This function
// may return a different value (depending on whether the method has
// been JITed or not. pAccessType is an in-out parameter. The JIT
// specifies what level of indirection it desires, and the EE sets it
// to what it can provide (which may not be the same).
virtual void __stdcall getFunctionEntryPoint(
CORINFO_METHOD_HANDLE ftn, /* IN */
InfoAccessType requestedAccessType, /* IN */
CORINFO_CONST_LOOKUP * pResult, /* OUT */
CORINFO_ACCESS_FLAGS accessFlags = CORINFO_ACCESS_ANY) = 0;
// return a directly callable address. This can be used similarly to the
// value returned by getFunctionEntryPoint() except that it is
// guaranteed to be the same for a given function.
// pAccessType is an in-out parameter. The JIT
// specifies what level of indirection it desires, and the EE sets it
// to what it can provide (which may not be the same).
virtual void __stdcall getFunctionFixedEntryPointInfo(
CORINFO_MODULE_HANDLE scopeHnd,
unsigned metaTOK,
CORINFO_CONTEXT_HANDLE context,
CORINFO_LOOKUP * pResult) = 0;
// get the syncronization handle that is passed to monXstatic function
virtual void* __stdcall getMethodSync(
CORINFO_METHOD_HANDLE ftn,
void **ppIndirection = NULL
) = 0;
// These entry points must be called if a handle is being embedded in
// the code to be passed to a JIT helper function. (as opposed to just
// being passed back into the ICorInfo interface.)
// a module handle may not always be available. A call to embedModuleHandle should always
// be preceeded by a call to canEmbedModuleHandleForHelper. A dynamicMethod does not have a module
virtual bool __stdcall canEmbedModuleHandleForHelper(
CORINFO_MODULE_HANDLE handle
) = 0;
virtual CORINFO_MODULE_HANDLE __stdcall embedModuleHandle(
CORINFO_MODULE_HANDLE handle,
void **ppIndirection = NULL
) = 0;
virtual CORINFO_CLASS_HANDLE __stdcall embedClassHandle(
CORINFO_CLASS_HANDLE handle,
void **ppIndirection = NULL
) = 0;
virtual CORINFO_METHOD_HANDLE __stdcall embedMethodHandle(
CORINFO_METHOD_HANDLE handle,
void **ppIndirection = NULL
) = 0;
virtual CORINFO_FIELD_HANDLE __stdcall embedFieldHandle(
CORINFO_FIELD_HANDLE handle,
void **ppIndirection = NULL
) = 0;
// Given a module scope (module), a method handle (context) and
// a metadata token (metaTOK), fetch the handle
// (type, field or method) associated with the token.
// If this is not possible at compile-time (because the current method's
// code is shared and the token contains generic parameters)
// then indicate how the handle should be looked up at run-time.
//
// Type tokens can be combined with CORINFO_ANNOT_MASK flags
// to obtain array type handles. These are typically required by the 'newarr'
// instruction which takes a token for the *element* type of the array.
//
// Similarly method tokens can be combined with CORINFO_ANNOT_MASK flags
// method entry points. These are typically required by the 'call' and 'ldftn'
// instructions.
//
// Byrefs or System.Void should only occur in method and local signatures, which
// are accessed using ICorClassInfo and ICorClassInfo.getChildType. ldtoken is one
// exception from this rule. allowAllTypes should be set to true only for ldtoken only!
//
virtual void __stdcall embedGenericHandle(
CORINFO_MODULE_HANDLE module,
unsigned metaTOK,
CORINFO_CONTEXT_HANDLE context,
CorInfoTokenKind tokenKind,
CORINFO_GENERICHANDLE_RESULT *pResult) = 0;
// Return information used to locate the exact enclosing type of the current method.
// Used only to invoke .cctor method from code shared across generic instantiations
// !needsRuntimeLookup statically known (enclosing type of method itself)
// needsRuntimeLookup:
// CORINFO_LOOKUP_THISOBJ use vtable pointer of 'this' param
// CORINFO_LOOKUP_CLASSPARAM use vtable hidden param
// CORINFO_LOOKUP_METHODPARAM use enclosing type of method-desc hidden param
virtual CORINFO_LOOKUP_KIND __stdcall getLocationOfThisType(
CORINFO_METHOD_HANDLE context
) = 0;
// return the unmanaged target *if method has already been prelinked.*
virtual void* __stdcall getPInvokeUnmanagedTarget(
CORINFO_METHOD_HANDLE method,
void **ppIndirection = NULL
) = 0;
// return address of fixup area for late-bound PInvoke calls.
virtual void* __stdcall getAddressOfPInvokeFixup(
CORINFO_METHOD_HANDLE method,
void **ppIndirection = NULL
) = 0;
// Generate a cookie based on the signature that would needs to be passed
// to CORINFO_HELP_PINVOKE_CALLI
virtual LPVOID GetCookieForPInvokeCalliSig(
CORINFO_SIG_INFO* szMetaSig,
void ** ppIndirection = NULL
) = 0;
// Gets a handle that is checked to see if the current method is
// included in "JustMyCode"
virtual CORINFO_JUST_MY_CODE_HANDLE __stdcall getJustMyCodeHandle(
CORINFO_METHOD_HANDLE method,
CORINFO_JUST_MY_CODE_HANDLE**ppIndirection = NULL
) = 0;
// Gets a method handle that can be used to correlate profiling data.
// This is the IP of a native method, or the address of the descriptor struct
// for IL. Always guaranteed to be unique per process, and not to move. */
virtual void __stdcall GetProfilingHandle(
CORINFO_METHOD_HANDLE method,
BOOL *pbHookFunction,
void **pEEHandle,
void **pProfilerHandle,
BOOL *pbIndirectedHandles
) = 0;
// returns the offset into the interface table
virtual unsigned __stdcall getInterfaceTableOffset (
CORINFO_CLASS_HANDLE cls,
void **ppIndirection = NULL
) = 0;
//return the address of a pointer to a callable stub that will do the virtual or interface call
//
// When inlining methodBeingCompiledHnd should be the originating caller in a sequence of nested
// inlines, e.g. it is used to determine if the code being generated is domain
// neutral or not.
virtual void __stdcall getCallInfo(
CORINFO_METHOD_HANDLE methodBeingCompiledHnd,
CORINFO_MODULE_HANDLE tokenScope,
unsigned methodToken,
unsigned constraintToken, // the type token from a preceding constraint. prefix instruction (if any)
CORINFO_CONTEXT_HANDLE tokenContext,
CORINFO_CALLINFO_FLAGS flags,
CORINFO_CALL_INFO *pResult) = 0;
// Returns TRUE if the Class Domain ID is the RID of the class (currently true for every class
// except reflection emitted classes and generics)
virtual BOOL __stdcall isRIDClassDomainID(CORINFO_CLASS_HANDLE cls) = 0;
// returns the class's domain ID for accessing shared statics
virtual unsigned __stdcall getClassDomainID (
CORINFO_CLASS_HANDLE cls,
void **ppIndirection = NULL
) = 0;
virtual size_t __stdcall getModuleDomainID (
CORINFO_MODULE_HANDLE module,
void **ppIndirection = NULL
) = 0;
// return the data's address (for static fields only)
virtual void* __stdcall getFieldAddress(
CORINFO_FIELD_HANDLE field,
void **ppIndirection = NULL
) = 0;
// registers a vararg sig & returns a VM cookie for it (which can contain other stuff)
virtual CORINFO_VARARGS_HANDLE __stdcall getVarArgsHandle(
CORINFO_SIG_INFO *pSig,
void **ppIndirection = NULL
) = 0;
// Allocate a string literal on the heap and return a handle to it
virtual InfoAccessType __stdcall constructStringLiteral(
CORINFO_MODULE_HANDLE module,
mdToken metaTok,
void **ppInfo
) = 0;
// (static fields only) given that 'field' refers to thread local store,
// return the ID (TLS index), which is used to find the begining of the
// TLS data area for the particular DLL 'field' is associated with.
virtual DWORD __stdcall getFieldThreadLocalStoreID (
CORINFO_FIELD_HANDLE field,
void **ppIndirection = NULL
) = 0;
// returns the class typedesc given a methodTok (needed for arrays since
// they share a common method table, so we can't use getMethodClass)
virtual CORINFO_CLASS_HANDLE __stdcall findMethodClass(
CORINFO_MODULE_HANDLE module,
mdToken methodTok,
CORINFO_METHOD_HANDLE context
) = 0;
// Sets another object to intercept calls to "self"
virtual void __stdcall setOverride(
ICorDynamicInfo *pOverride
) = 0;
// Adds an active dependency from the context method's module to the given module
virtual void __stdcall addActiveDependency(
CORINFO_MODULE_HANDLE moduleFrom,
CORINFO_MODULE_HANDLE moduleTo
) = 0;
virtual CORINFO_METHOD_HANDLE __stdcall GetDelegateCtor(
CORINFO_METHOD_HANDLE methHnd,
CORINFO_CLASS_HANDLE clsHnd,
CORINFO_METHOD_HANDLE targetMethodHnd,
DelegateCtorArgs * pCtorData
) = 0;
virtual void __stdcall MethodCompileComplete(
CORINFO_METHOD_HANDLE methHnd
) = 0;
};
/**********************************************************************************/
#define IA64_BUNDLE_SIZE 16
#if defined(_X86_)
#define HARDBOUND_DYNAMIC_CALLS
#endif
#if defined(_X86_) || defined(_PPC_)
#define HELPER_TABLE_ENTRY_LEN 8
#define HELPER_TABLE_ALIGN 8
#else
#error "Unknown target"
#endif // _IA64_
#endif // _COR_INFO_H_
| 43.739953 | 277 | 0.634379 | [
"object",
"model",
"transform"
] |
bd4536a2ff1b2bd86b2737cc07f9b5891ed22eee | 26,641 | c | C | upwork-devs/son-ha/c-icap/c-icap/mem.c | anejaalekh/s-k8-proxy-rebuild | bd690ece306ba8ae81ce027e5fb8ee933cce1748 | [
"Apache-2.0"
] | null | null | null | upwork-devs/son-ha/c-icap/c-icap/mem.c | anejaalekh/s-k8-proxy-rebuild | bd690ece306ba8ae81ce027e5fb8ee933cce1748 | [
"Apache-2.0"
] | null | null | null | upwork-devs/son-ha/c-icap/c-icap/mem.c | anejaalekh/s-k8-proxy-rebuild | bd690ece306ba8ae81ce027e5fb8ee933cce1748 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2004-2008 Christos Tsantilas
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*/
#include "common.h"
#include "c-icap.h"
#include <stdio.h>
#include <fcntl.h>
#include <ctype.h>
#include "ci_threads.h"
#include "debug.h"
#include "mem.h"
#include <assert.h>
int ci_buffers_init();
/*General Functions */
ci_mem_allocator_t *default_allocator = NULL;
int MEM_ALLOCATOR_POOL = -1;
int PACK_ALLOCATOR_POOL = -1;
static size_t sizeof_pack_allocator();
ci_mem_allocator_t *ci_create_pool_allocator(int items_size);
CI_DECLARE_FUNC(int) mem_init()
{
int ret = -1;
ret = ci_buffers_init();
default_allocator = ci_create_os_allocator();
if (!default_allocator && ret ==-1)
ret = 0;
MEM_ALLOCATOR_POOL = ci_object_pool_register("ci_mem_allocator_t", sizeof(ci_mem_allocator_t));
assert(MEM_ALLOCATOR_POOL >= 0);
PACK_ALLOCATOR_POOL = ci_object_pool_register("pack_allocator_t", sizeof_pack_allocator());
assert(PACK_ALLOCATOR_POOL >= 0);
return ret;
}
void mem_reset()
{
}
void ci_mem_allocator_destroy(ci_mem_allocator_t *allocator)
{
allocator->destroy(allocator);
/*space for ci_mem_allocator_t struct is not always allocated
using malloc */
if (allocator->must_free == 1)
free(allocator);
else if (allocator->must_free == 2)
ci_object_pool_free(allocator);
/*
else if (allocator->must_free == 0)
user is responsible to release the struct
*/
}
/******************/
static ci_mem_allocator_t *alloc_mem_allocator_struct()
{
ci_mem_allocator_t *alc;
if (MEM_ALLOCATOR_POOL < 0) {
alc = (ci_mem_allocator_t *) malloc(sizeof(ci_mem_allocator_t));
alc->must_free = 1;
} else {
alc = ci_object_pool_alloc(MEM_ALLOCATOR_POOL);
alc->must_free = 2;
}
return alc;
}
/*******************************************************************/
/* Buffers pool api functions */
#define BUF_SIGNATURE 0xAA55
struct mem_buffer_block {
uint16_t sig;
int ID;
union {
double __align;
char ptr[1];
} data;
};
#define offsetof(type,member) ((size_t) &((type*)0)->member)
#define PTR_OFFSET offsetof(struct mem_buffer_block,data.ptr[0])
ci_mem_allocator_t *short_buffers[16];
ci_mem_allocator_t *long_buffers[16];
int ci_buffers_init()
{
int i;
ci_mem_allocator_t *buf64_pool, *buf128_pool,
*buf256_pool,*buf512_pool, *buf1024_pool;
ci_mem_allocator_t *buf2048_pool, *buf4096_pool,
*buf8192_pool, *buf16384_pool, *buf32768_pool;
buf64_pool = ci_create_pool_allocator(64+PTR_OFFSET);
buf128_pool = ci_create_pool_allocator(128+PTR_OFFSET);
buf256_pool = ci_create_pool_allocator(256+PTR_OFFSET);
buf512_pool = ci_create_pool_allocator(512+PTR_OFFSET);
buf1024_pool = ci_create_pool_allocator(1024+PTR_OFFSET);
buf2048_pool = ci_create_pool_allocator(2048+PTR_OFFSET);
buf4096_pool = ci_create_pool_allocator(4096+PTR_OFFSET);
buf8192_pool = ci_create_pool_allocator(8192+PTR_OFFSET);
buf16384_pool = ci_create_pool_allocator(16384+PTR_OFFSET);
buf32768_pool = ci_create_pool_allocator(32768+PTR_OFFSET);
short_buffers[0] = buf64_pool;
short_buffers[1] = buf128_pool;
short_buffers[2] = short_buffers[3] = buf256_pool;
short_buffers[4] = short_buffers[5] =
short_buffers[6] = short_buffers[7] = buf512_pool;
for (i = 8; i < 16; i++)
short_buffers[i] = buf1024_pool;
long_buffers[0] = buf2048_pool;
long_buffers[1] = buf4096_pool;
long_buffers[2] = long_buffers[3] = buf8192_pool;
long_buffers[4] = long_buffers[5] =
long_buffers[6] = long_buffers[7] = buf16384_pool;
for (i = 8; i < 16; i++)
long_buffers[i] = buf32768_pool;
return 1;
}
int short_buffer_sizes[16] = {
64,
128,
256,256,
512, 512, 512, 512,
1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024
};
int long_buffer_sizes[16] = {
2048,
4096,
8192, 8192,
16384, 16384, 16384, 16384,
32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768
};
void ci_buffers_destroy()
{
int i;
for (i = 0; i < 16; i++) {
if (short_buffers[i] != NULL)
ci_mem_allocator_destroy(short_buffers[i]);
}
}
void *ci_buffer_alloc(int block_size)
{
int type, size;
struct mem_buffer_block *block = NULL;
size = block_size + PTR_OFFSET;
type = (block_size-1) >> 6;
if (type< 16 && short_buffers[type] != NULL) {
block = short_buffers[type]->alloc(short_buffers[type], size);
} else if (type < 512) {
type = type >> 5;
if (long_buffers[type] != NULL) {
block = long_buffers[type]->alloc(long_buffers[type], size);
}
}
if (!block)
block = (struct mem_buffer_block *)malloc(size);
if (!block) {
ci_debug_printf(1, "Failed to allocate space for buffer of size:%d\n", block_size);
return NULL;
}
block->sig = BUF_SIGNATURE;
block->ID = block_size;
ci_debug_printf(8, "Geting buffer from pool %d:%d\n", block_size, type);
return (void *)block->data.ptr;
}
size_t ci_buffer_blocksize(const void *data)
{
const struct mem_buffer_block *block;
int type;
size_t buffer_block_size = 0;
block = (const struct mem_buffer_block *)(data-PTR_OFFSET);
if (block->sig != BUF_SIGNATURE) {
ci_debug_printf(1,"ci_buffer_blocksize: ERROR, %p is not internal buffer. This is a bug!!!!\n", data);
return 0;
}
type = (block->ID - 1) >> 6;
if (type< 16 && short_buffers[type] != NULL) {
buffer_block_size = short_buffer_sizes[type];
} else if (type < 512) {
type = type >> 5;
if (long_buffers[type] != NULL) {
buffer_block_size = long_buffer_sizes[type];
}
}
if (!buffer_block_size)
buffer_block_size = block->ID;
return buffer_block_size;
}
void * ci_buffer_realloc(void *data, int block_size)
{
int buffer_size = 0;
struct mem_buffer_block *block;
if (!data)
return ci_buffer_alloc(block_size);
block = (struct mem_buffer_block *)(data-PTR_OFFSET);
if (block->sig != BUF_SIGNATURE) {
ci_debug_printf(1,"ci_buffer_realloc: ERROR, %p is not internal buffer. This is a bug!!!!\n", data);
return NULL;
}
buffer_size = ci_buffer_blocksize(data);
assert(buffer_size > 0);
ci_debug_printf(8, "Current block size for realloc: %d, requested block size: %d. The initial size: %d\n",
buffer_size, block_size, block->ID);
/*If no block_size created than our buffer actual size probably requires a realloc.....*/
if (block_size > buffer_size) {
ci_debug_printf(10, "We are going to allocate a bigger block of size: %d\n", block_size);
data = ci_buffer_alloc(block_size);
if (!data)
return NULL;
ci_debug_printf(10, "Preserve data of size: %d\n", block->ID);
memcpy(data, block->data.ptr, block->ID);
ci_buffer_free(block->data.ptr);
} else {
/*we neeed to update block->ID to the new requested size...*/
block->ID = block_size;
}
return data;
}
void ci_buffer_free(void *data)
{
int block_size, type;
struct mem_buffer_block *block;
if (!data)
return;
block = (struct mem_buffer_block *)(data-PTR_OFFSET);
if (block->sig != BUF_SIGNATURE) {
ci_debug_printf(1,"ci_buffer_free: ERROR, %p is not internal buffer. This is a bug!!!!\n", data);
return;
}
block_size = block->ID;
type = (block_size-1) >> 6;
if (type < 16 && short_buffers[type] != NULL) {
short_buffers[type]->free(short_buffers[type], block);
ci_debug_printf(8, "Store buffer to short pool %d:%d\n", block_size, type);
} else if (type < 512) {
type = type >> 5;
if (long_buffers[type] != NULL)
long_buffers[type]->free(long_buffers[type], block);
else
free(block);
ci_debug_printf(8, "Store buffer to long pool %d:%d\n", block_size, type);
} else {
free(block);
}
}
/*******************************************************************/
/*Object pools */
#define OBJ_SIGNATURE 0x55AA
ci_mem_allocator_t **object_pools = NULL;
int object_pools_size = 0;
int object_pools_used = 0;
int ci_object_pools_init()
{
return 1;
}
void ci_object_pools_destroy()
{
int i;
for (i = 0; i < object_pools_used; i++) {
if (object_pools[i] != NULL)
ci_mem_allocator_destroy(object_pools[i]);
}
}
#define STEP 128
int ci_object_pool_register(const char *name, int size)
{
int ID, i;
ID = -1;
/*search for an empty position on object_pools and assign here?*/
if (object_pools == NULL) {
object_pools = malloc(STEP*sizeof(ci_mem_allocator_t *));
object_pools_size = STEP;
ID = 0;
} else {
for (i = 0; i < object_pools_used; i++) {
if (object_pools[i] == NULL) {
ID = i;
break;
}
}
if (ID == -1) {
if (object_pools_size == object_pools_used) {
object_pools_size += STEP;
object_pools = realloc(object_pools, object_pools_size*sizeof(ci_mem_allocator_t *));
}
ID=object_pools_used;
}
}
if (object_pools == NULL) //??????
return -1;
object_pools[ID] = ci_create_pool_allocator(size+PTR_OFFSET);
object_pools_used++;
return ID;
}
void ci_object_pool_unregister(int id)
{
if (id >= object_pools_used || id < 0) {
/*A error message ....*/
return;
}
if (object_pools[id]) {
ci_mem_allocator_destroy(object_pools[id]);
object_pools[id] = NULL;
}
}
void *ci_object_pool_alloc(int id)
{
struct mem_buffer_block *block = NULL;
if (id >= object_pools_used || id < 0 || !object_pools[id]) {
/*A error message ....*/
ci_debug_printf(1, "Invalid object pool %d. This is a BUG!\n", id);
return NULL;
}
block = object_pools[id]->alloc(object_pools[id], 1/*A small size smaller than obj size*/);
if (!block) {
ci_debug_printf(2, "Failed to allocate object from pool %d\n", id);
return NULL;
}
ci_debug_printf(8, "Allocating from objects pool object %d\n", id);
block->sig = OBJ_SIGNATURE;
block->ID = id;
return (void *)block->data.ptr;
}
void ci_object_pool_free(void *ptr)
{
struct mem_buffer_block *block = (struct mem_buffer_block *)(ptr-PTR_OFFSET);
if (block->sig != OBJ_SIGNATURE) {
ci_debug_printf(1,"ci_object_pool_free: ERROR, %p is not internal buffer. This is a bug!!!!\n", ptr);
return;
}
if (block->ID > object_pools_used || block->ID < 0 || !object_pools[block->ID]) {
ci_debug_printf(1,"ci_object_pool_free: ERROR, %p is pointing to corrupted mem? This is a bug!!!!\n", ptr);
return;
}
ci_debug_printf(8, "Storing to objects pool object %d\n", block->ID);
object_pools[block->ID]->free(object_pools[block->ID], block);
}
/*******************************************************************/
/*A simple allocator implementation which uses the system malloc */
static void *os_allocator_alloc(ci_mem_allocator_t *allocator,size_t size)
{
return malloc(size);
}
static void os_allocator_free(ci_mem_allocator_t *allocator,void *p)
{
free(p);
}
static void os_allocator_reset(ci_mem_allocator_t *allocator)
{
/*nothing to do*/
}
static void os_allocator_destroy(ci_mem_allocator_t *allocator)
{
/*nothing to do*/
}
ci_mem_allocator_t *ci_create_os_allocator()
{
ci_mem_allocator_t *allocator = alloc_mem_allocator_struct();
if (!allocator)
return NULL;
allocator->alloc = os_allocator_alloc;
allocator->free = os_allocator_free;
allocator->reset = os_allocator_reset;
allocator->destroy = os_allocator_destroy;
allocator->data = NULL;
allocator->name = NULL;
allocator->type = OS_ALLOC;
return allocator;
}
/************************************************************/
/* The serial allocator implementation */
typedef struct serial_allocator {
void *memchunk;
void *curpos;
void *endpos;
struct serial_allocator *next;
} serial_allocator_t;
static serial_allocator_t *serial_allocator_build(int size)
{
serial_allocator_t *serial_alloc;
void *buffer;
size = _CI_ALIGN(size);
/*The serial_allocator and mem_allocator structures will be
allocated in the buffer */
if (size < sizeof(serial_allocator_t) + sizeof(ci_mem_allocator_t))
return NULL;
buffer = ci_buffer_alloc(size);
serial_alloc = buffer;
/*The allocated block size maybe is larger, than the requested.
Lets fix size to actual block size: */
size = ci_buffer_blocksize(buffer);
serial_alloc->memchunk = buffer + sizeof(serial_allocator_t);
size -= sizeof(serial_allocator_t);
serial_alloc->curpos = serial_alloc->memchunk;
serial_alloc->endpos = serial_alloc->memchunk + size;
serial_alloc->next = NULL;
return serial_alloc;
}
static void *serial_allocation(serial_allocator_t *serial_alloc, size_t size)
{
int max_size;
void *mem;
size = _CI_ALIGN(size); /*round size to a correct alignment size*/
max_size = serial_alloc->endpos - serial_alloc->memchunk;
if (size > max_size)
return NULL;
while (size > (serial_alloc->endpos - serial_alloc->curpos)) {
if (serial_alloc->next == NULL) {
serial_alloc->next = serial_allocator_build(max_size);
if (!serial_alloc->next)
return NULL;
}
serial_alloc = serial_alloc->next;
}
mem = serial_alloc->curpos;
serial_alloc->curpos += size;
return mem;
}
static void *serial_allocator_alloc(ci_mem_allocator_t *allocator,size_t size)
{
serial_allocator_t *serial_alloc = (serial_allocator_t *)allocator->data;
if (!serial_alloc)
return NULL;
return serial_allocation(serial_alloc, size);
}
static void serial_allocator_free(ci_mem_allocator_t *allocator,void *p)
{
/* We can not free :-) */
}
static void serial_allocator_reset(ci_mem_allocator_t *allocator)
{
serial_allocator_t *serial_alloc, *sa;
void *tmp;
serial_alloc = (serial_allocator_t *)allocator->data;
serial_alloc->curpos = serial_alloc->memchunk + _CI_ALIGN(sizeof(ci_mem_allocator_t));
sa = serial_alloc->next;
serial_alloc->next = NULL;
/*release any other allocated chunk*/
while (sa) {
tmp = (void *)sa;
ci_buffer_free(tmp);
sa = sa->next;
}
}
static void serial_allocator_destroy(ci_mem_allocator_t *allocator)
{
serial_allocator_t *cur, *next;
if (!allocator->data)
return;
cur = (serial_allocator_t *)allocator->data;
next = cur->next;
while (cur) {
ci_buffer_free((void *)cur);
cur = next;
if (next)
next = next->next;
}
}
ci_mem_allocator_t *ci_create_serial_allocator(int size)
{
ci_mem_allocator_t *allocator;
serial_allocator_t *sdata= serial_allocator_build(size);
/*Allocate space for ci_mem_allocator_t from our serial allocator ...*/
allocator = serial_allocation(sdata, sizeof(ci_mem_allocator_t));
if (!allocator) {
ci_buffer_free((void *)sdata);
return NULL;
}
allocator->alloc = serial_allocator_alloc;
allocator->free = serial_allocator_free;
allocator->reset = serial_allocator_reset;
allocator->destroy = serial_allocator_destroy;
allocator->data = sdata;
allocator->name = NULL;
allocator->type = SERIAL_ALLOC;
/*It is allocated in our buffer space...*/
allocator->must_free = 0;
return allocator;
}
/****************************************************************/
typedef struct pack_allocator {
void *memchunk;
void *curpos;
void *endpos;
void *end;
int must_free;
} pack_allocator_t;
/*Api functions for pack allocator:*/
void *ci_pack_allocator_alloc_unaligned(ci_mem_allocator_t *allocator, size_t size)
{
int max_size;
void *mem;
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
if (!pack_alloc)
return NULL;
max_size = pack_alloc->endpos - pack_alloc->curpos;
if (size > max_size)
return NULL;
mem = pack_alloc->curpos;
pack_alloc->curpos += size;
return mem;
}
void *ci_pack_allocator_alloc(ci_mem_allocator_t *allocator,size_t size)
{
size = _CI_ALIGN(size); /*round size to a correct alignment size*/
return ci_pack_allocator_alloc_unaligned(allocator, size);
}
void *ci_pack_allocator_alloc_from_rear(ci_mem_allocator_t *allocator, int size)
{
int max_size;
void *mem;
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
if (!pack_alloc)
return NULL;
size = _CI_ALIGN(size); /*round size to a correct alignment size*/
max_size = pack_alloc->endpos - pack_alloc->curpos;
if (size > max_size)
return NULL;
pack_alloc->endpos -= size; /*Allocate block from the end of memory block*/
mem = pack_alloc->endpos;
return mem;
}
void ci_pack_allocator_free(ci_mem_allocator_t *allocator,void *p)
{
/* We can not free :-) */
}
void ci_pack_allocator_reset(ci_mem_allocator_t *allocator)
{
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
pack_alloc->curpos = pack_alloc->memchunk;
pack_alloc->endpos = pack_alloc->end;
}
void ci_pack_allocator_destroy(ci_mem_allocator_t *allocator)
{
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
if (pack_alloc->must_free != 0) {
ci_object_pool_free(allocator->data);
allocator->data = NULL;
}
}
/*If "off" is not aligned return the first smaller aligned offset*/
#define _ALIGNED_OFFSET(off) (off != _CI_ALIGN(off) ? _CI_ALIGN(off - _CI_NBYTES_ALIGNMENT) : off)
ci_mem_allocator_t *init_pack_allocator(ci_mem_allocator_t *allocator, pack_allocator_t *pack_alloc, char *memblock, size_t size, int free)
{
/*We may not be able to use all of the memblock size.
We need to support allocating memory space from the end, so we
need to have aligned the pack_alloc->end to correctly calculate
memory block offsets from the end in ci_pack_allocator_alloc_from_rear
function.
*/
size = _ALIGNED_OFFSET(size);
pack_alloc->memchunk = memblock;
pack_alloc->curpos =pack_alloc->memchunk;
pack_alloc->end = pack_alloc->memchunk + size;
pack_alloc->endpos = pack_alloc->end;
pack_alloc->must_free = free;
allocator->alloc = ci_pack_allocator_alloc;
allocator->free = ci_pack_allocator_free;
allocator->reset = ci_pack_allocator_reset;
allocator->destroy = ci_pack_allocator_destroy;
allocator->data = pack_alloc;
allocator->name = NULL;
allocator->type = PACK_ALLOC;
allocator->must_free = free;
return allocator;
}
ci_mem_allocator_t *ci_create_pack_allocator(char *memblock, size_t size)
{
ci_mem_allocator_t *allocator;
pack_allocator_t *pack_alloc;
pack_alloc = ci_object_pool_alloc(PACK_ALLOCATOR_POOL);
if (!pack_alloc)
return NULL;
allocator = alloc_mem_allocator_struct();
if (!allocator) {
ci_object_pool_free(pack_alloc);
return NULL;
}
return init_pack_allocator(allocator, pack_alloc, memblock, size, 2);
}
/*similar to the above but allocates required space for pack_allocator on the given memblock*/
ci_mem_allocator_t *ci_create_pack_allocator_on_memblock(char *memblock, size_t size)
{
ci_mem_allocator_t *allocator;
/*We need to allocate space on memblock for internal structures*/
if (size <= (_CI_ALIGN(sizeof(pack_allocator_t)) + _CI_ALIGN(sizeof(ci_mem_allocator_t))))
return NULL;
pack_allocator_t *pack_alloc = (pack_allocator_t *)memblock;
memblock += _CI_ALIGN(sizeof(pack_allocator_t));
size -= _CI_ALIGN(sizeof(pack_allocator_t));
allocator = (ci_mem_allocator_t *)memblock;
memblock += _CI_ALIGN(sizeof(ci_mem_allocator_t));
size -= _CI_ALIGN(sizeof(ci_mem_allocator_t));
return init_pack_allocator(allocator, pack_alloc, memblock, size, 0);
}
int ci_pack_allocator_data_size(ci_mem_allocator_t *allocator)
{
assert(allocator->type == PACK_ALLOC);
pack_allocator_t *pack_alloc = (pack_allocator_t *)allocator->data;
return (int) (pack_alloc->curpos - pack_alloc->memchunk) +
(pack_alloc->end - pack_alloc->endpos);
}
size_t ci_pack_allocator_required_size()
{
return _CI_ALIGN(sizeof(pack_allocator_t)) + _CI_ALIGN(sizeof(ci_mem_allocator_t));
}
static size_t sizeof_pack_allocator() {return sizeof(pack_allocator_t);}
void ci_pack_allocator_set_start_pos(ci_mem_allocator_t *allocator, void *p)
{
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
assert(p >= pack_alloc->memchunk);
pack_alloc->curpos = p;
}
void ci_pack_allocator_set_end_pos(ci_mem_allocator_t *allocator, void *p)
{
pack_allocator_t *pack_alloc;
assert(allocator->type == PACK_ALLOC);
pack_alloc = (pack_allocator_t *)allocator->data;
assert(p <= pack_alloc->end);
if (p == NULL)
pack_alloc->endpos = pack_alloc->end;
else
pack_alloc->endpos = p;
}
/****************************************************************/
struct mem_block_item {
void *data;
struct mem_block_item *next;
};
struct pool_allocator {
int items_size;
int strict;
int alloc_count;
int hits_count;
ci_thread_mutex_t mutex;
struct mem_block_item *free;
struct mem_block_item *allocated;
};
static struct pool_allocator *pool_allocator_build(int items_size,
int strict)
{
struct pool_allocator *palloc;
palloc = (struct pool_allocator *)malloc(sizeof(struct pool_allocator));
if (!palloc) {
return NULL;
}
palloc->items_size = items_size;
palloc->strict = strict;
palloc->free = NULL;
palloc->allocated = NULL;
palloc->alloc_count = 0;
palloc->hits_count = 0;
ci_thread_mutex_init(&palloc->mutex);
return palloc;
}
static void *pool_allocator_alloc(ci_mem_allocator_t *allocator,size_t size)
{
struct mem_block_item *mem_item;
void *data = NULL;
struct pool_allocator *palloc = (struct pool_allocator *)allocator->data;
if (size > palloc->items_size)
return NULL;
ci_thread_mutex_lock(&palloc->mutex);
if (palloc->free) {
mem_item = palloc->free;
palloc->free=palloc->free->next;
data = mem_item->data;
mem_item->data = NULL;
palloc->hits_count++;
} else {
mem_item = malloc(sizeof(struct mem_block_item));
mem_item->data = NULL;
data = malloc(palloc->items_size);
palloc->alloc_count++;
}
mem_item->next = palloc->allocated;
palloc->allocated = mem_item;
ci_thread_mutex_unlock(&palloc->mutex);
ci_debug_printf(8, "pool hits: %d allocations: %d\n", palloc->hits_count, palloc->alloc_count);
return data;
}
static void pool_allocator_free(ci_mem_allocator_t *allocator,void *p)
{
struct mem_block_item *mem_item;
struct pool_allocator *palloc = (struct pool_allocator *)allocator->data;
ci_thread_mutex_lock(&palloc->mutex);
if (!palloc->allocated) {
/*Yes can happen! after a reset but users did not free all objects*/
free(p);
} else {
mem_item = palloc->allocated;
palloc->allocated = palloc->allocated->next;
mem_item->data = p;
mem_item->next = palloc->free;
palloc->free = mem_item;
}
ci_thread_mutex_unlock(&palloc->mutex);
}
static void pool_allocator_reset(ci_mem_allocator_t *allocator)
{
struct mem_block_item *mem_item, *cur;
struct pool_allocator *palloc = (struct pool_allocator *)allocator->data;
ci_thread_mutex_lock(&palloc->mutex);
if (palloc->allocated) {
mem_item = palloc->allocated;
while (mem_item != NULL) {
cur = mem_item;
mem_item = mem_item->next;
free(cur);
}
}
palloc->allocated = NULL;
if (palloc->free) {
mem_item = palloc->free;
while (mem_item != NULL) {
cur = mem_item;
mem_item = mem_item->next;
free(cur->data);
free(cur);
}
}
palloc->free = NULL;
ci_thread_mutex_unlock(&palloc->mutex);
}
static void pool_allocator_destroy(ci_mem_allocator_t *allocator)
{
pool_allocator_reset(allocator);
struct pool_allocator *palloc = (struct pool_allocator *)allocator->data;
ci_thread_mutex_destroy(&palloc->mutex);
free(palloc);
}
ci_mem_allocator_t *ci_create_pool_allocator(int items_size)
{
struct pool_allocator *palloc;
ci_mem_allocator_t *allocator;
palloc = pool_allocator_build(items_size, 0);
/*Use always malloc for ci_mem_alocator struct.*/
allocator = (ci_mem_allocator_t *) malloc(sizeof(ci_mem_allocator_t));
if (!allocator)
return NULL;
allocator->alloc = pool_allocator_alloc;
allocator->free = pool_allocator_free;
allocator->reset = pool_allocator_reset;
allocator->destroy = pool_allocator_destroy;
allocator->data = palloc;
allocator->name = NULL;
allocator->type = POOL_ALLOC;
allocator->must_free = 1;
return allocator;
}
| 29.502769 | 139 | 0.653842 | [
"object"
] |
bd45e748eddd9788c4c038f216585c2b3e7cc50a | 7,343 | h | C | src/sim/include/cphsi.h | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/sim/include/cphsi.h | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/sim/include/cphsi.h | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #ifndef _CPHSI_H
#define _CPHSI_H
#include "cpobject.h"
#include "navsystem.h"
#ifdef USE_SH_POOLS
extern MEM_POOL gCockMemPool;
#endif
const float COMPASS_X_CENTER = 0.0F;
const float COMPASS_Y_CENTER = -0.1F;
const float HALFPI = 1.5708F;
const float TWOPI = 6.2832F;
const int NORMAL_HSI_CRS_STATE = 7;
const int NORMAL_HSI_HDG_STATE = 7;
enum HSIColors
{
HSI_COLOR_ARROWS,
HSI_COLOR_ARROWGHOST,
HSI_COLOR_COURSEWARN,
HSI_COLOR_HEADINGMARK,
HSI_COLOR_STATIONBEARING,
HSI_COLOR_COURSE,
HSI_COLOR_AIRCRAFT,
HSI_COLOR_CIRCLES,
HSI_COLOR_DEVBAR,
HSI_COLOR_ILSDEVWARN,
HSI_COLOR_TOTAL
};
//====================================================
// Predeclarations
//====================================================
class CPObject;
class CPHsi;
//====================================================
// Structures used for HSI Initialization
//====================================================
typedef struct
{
int compassTransparencyType;
RECT compassSrc;
RECT compassDest;
RECT devSrc;
RECT devDest;
RECT warnFlag;
CPHsi *pHsi;
long colors[HSI_COLOR_TOTAL];
BYTE *sourcehsi; //Wombat778 3-24-04
} HsiInitStr;
//====================================================
// CPHsi Class Definition
//====================================================
class CPHsi
{
#ifdef USE_SH_POOLS
public:
// Overload new/delete to use a SmartHeap pool
void *operator new(size_t size)
{
return MemAllocPtr(gCockMemPool, size, FALSE);
};
void operator delete(void *mem)
{
if (mem) MemFreePtr(mem);
};
#endif
public:
//====================================================
// Button States
//====================================================
typedef enum HSIButtonStates
{
HSI_STA_CRS_STATE,
HSI_STA_HDG_STATE,
HSI_STA_TOTAL_STATES
};
//====================================================
// Horizontal Situaton Geometry
//====================================================
typedef enum HSIValues
{
HSI_VAL_CRS_DEVIATION,
HSI_VAL_DESIRED_CRS,
HSI_VAL_DISTANCE_TO_BEACON,
HSI_VAL_BEARING_TO_BEACON,
HSI_VAL_CURRENT_HEADING,
HSI_VAL_DESIRED_HEADING,
HSI_VAL_DEV_LIMIT,
HSI_VAL_HALF_DEV_LIMIT,
HSI_VAL_LOCALIZER_CRS,
HSI_VAL_AIRBASE_X,
HSI_VAL_AIRBASE_Y,
HSI_VAL_TOTAL_VALUES
};
//====================================================
// Control Flags
//====================================================
typedef enum HSIFlags
{
HSI_FLAG_TO_TRUE,
HSI_FLAG_ILS_WARN,
HSI_FLAG_CRS_WARN,
HSI_FLAG_INIT,
HSI_FLAG_TOTAL_FLAGS
};
//====================================================
// Constructors and Destructors
//====================================================
CPHsi();
//====================================================
// Runtime Public Member Functions
//====================================================
void Exec(void);
//====================================================
// Access Functions
//====================================================
void IncState(HSIButtonStates, float step = 5.0F); // MD -- 20040118: add default arg
void DecState(HSIButtonStates, float step = 5.0F); // MD -- 20040118: add default arg
int GetState(HSIButtonStates);
float GetValue(HSIValues);
BOOL GetFlag(HSIFlags);
// long mColor[2][HSI_COLOR_TOTAL];
//MI 02/02/02
float LastHSIHeading;
private:
//====================================================
// Internal Data
//====================================================
CockpitManager *mpCPManager;
int mpHsiStates[HSI_STA_TOTAL_STATES];
float mpHsiValues[HSI_VAL_TOTAL_VALUES];
BOOL mpHsiFlags[HSI_FLAG_TOTAL_FLAGS];
NavigationSystem::Instrument_Mode mLastMode;
WayPointClass* mLastWaypoint;
VU_TIME lastCheck;
BOOL lastResult;
//====================================================
// Calculation Routines
//====================================================
void ExecNav(void);
void ExecTacan(void);
void ExecILSNav(void);
void ExecILSTacan(void);
void ExecBeaconProximity(float, float, float, float);
void CalcTCNCrsDev(float course);
void CalcILSCrsDev(float);
BOOL BeaconInRange(float rangeToBeacon, float nominalBeaconRange);
};
//====================================================
// Class Definition for CPHSIView
//====================================================
class CPHsiView: public CPObject
{
#ifdef USE_SH_POOLS
public:
// Overload new/delete to use a SmartHeap pool
void *operator new(size_t size)
{
return MemAllocPtr(gCockMemPool, size, FALSE);
};
void operator delete(void *mem)
{
if (mem) MemFreePtr(mem);
};
#endif
private:
//====================================================
// Pointers to the Outside World
//====================================================
CPHsi *mpHsi;
//====================================================
// Viewport Dimension Data
//====================================================
float mTop;
float mLeft;
float mBottom;
float mRight;
//====================================================
// Compass Dial Data
//====================================================
int mRadius;
RECT mDevSrc;
RECT mDevDest;
RECT mCompassSrc;
RECT mCompassDest;
RECT mWarnFlag;
int mCompassTransparencyType;
int *mpCompassCircle;
int mCompassXCenter;
int mCompassYCenter;
int mCompassWidth;
int mCompassHeight;
ImageBuffer *CompassBuffer; //Wombat778 10-06-2003 Added to hold temporary buffer for HSI autoscaling/rotation
ulong mColor[2][HSI_COLOR_TOTAL];
//====================================================
// Position Routines
//====================================================
void MoveToCompassCenter(void);
//====================================================
// Draw Routines for Needles
//====================================================
void DrawCourse(float, float);
void DrawStationBearing(float);
void DrawAircraftSymbol(void);
//====================================================
// Draw Routines for Flags
//====================================================
void DrawHeadingMarker(float);
void DrawCourseWarning(void);
void DrawToFrom(void);
public:
//====================================================
// Runtime Public Draw Routines
//====================================================
virtual void DisplayDraw(void);
virtual void DisplayBlit(void);
virtual void Exec(SimBaseClass*);
//Wombat778 3-24-04 Stuff for rendered hsi
void DisplayBlit3D();
GLubyte *mpSourceBuffer;
virtual void CreateLit(void);
//Wombat778 End
//====================================================
// Constructors and Destructors
//====================================================
CPHsiView(ObjectInitStr*, HsiInitStr*);
virtual ~CPHsiView();
};
#endif
| 24.807432 | 116 | 0.46752 | [
"geometry"
] |
bd464a2220d3959e10fc8da95b6a7595f0e3ca1b | 766 | h | C | csim/src/dynamicglutamatesynapsesynchan.h | Kirito56/lsm-matlab | bf1631031a7c2cb709ca476e458f85faa2a1f84d | [
"MIT"
] | null | null | null | csim/src/dynamicglutamatesynapsesynchan.h | Kirito56/lsm-matlab | bf1631031a7c2cb709ca476e458f85faa2a1f84d | [
"MIT"
] | 1 | 2021-12-02T09:00:37.000Z | 2021-12-02T09:00:37.000Z | csim/src/dynamicglutamatesynapsesynchan.h | Kirito56/lsm-matlab | bf1631031a7c2cb709ca476e458f85faa2a1f84d | [
"MIT"
] | null | null | null | /*! \file dynamicglutamatesynapsesynchan.h
** \brief Class definition of DynamicGlutamateSynapseSynchan
*/
#ifndef _DYNAMICGLUTAMATESYNAPSESYNCHAN_H_
#define _DYNAMICGLUTAMATESYNAPSESYNCHAN_H_
#include "glutamatesynapsesynchan.h"
#include "spikingneuron.h"
#include <math.h>
//! Base class for all dynamic spiking synapses with spike time dependent plasticity (STDP)
class DynamicGlutamateSynapseSynchan : public GlutamateSynapseSynchan {
DO_REGISTERING
public:
#include "dynamicsynapse.h"
public:
DynamicGlutamateSynapseSynchan(void);
virtual ~DynamicGlutamateSynapseSynchan(void);
virtual void reset(void);
//! Increase psr according the Markrams model
virtual void stdpChangePSR(void) { }
virtual int preSpikeHit(void);
};
#endif
| 21.885714 | 91 | 0.789817 | [
"model"
] |
bd47c0879a2b7d8af7b464ffa4db18a37da0b032 | 20,353 | c | C | orte/mca/state/orted/state_orted.c | OpenCMISS-Utilities/openmpi | a85e6327971419bda61fdfed4cfe46845092232a | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/state/orted/state_orted.c | OpenCMISS-Utilities/openmpi | a85e6327971419bda61fdfed4cfe46845092232a | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/state/orted/state_orted.c | OpenCMISS-Utilities/openmpi | a85e6327971419bda61fdfed4cfe46845092232a | [
"BSD-3-Clause-Open-MPI"
] | 3 | 2015-11-29T06:00:56.000Z | 2021-03-29T07:03:29.000Z | /*
* Copyright (c) 2011-2012 Los Alamos National Security, LLC.
* All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "orte_config.h"
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "opal/util/output.h"
#include "orte/mca/errmgr/errmgr.h"
#include "orte/mca/iof/iof.h"
#include "orte/mca/rml/rml.h"
#include "orte/mca/routed/routed.h"
#include "orte/util/session_dir.h"
#include "orte/runtime/orte_quit.h"
#include "orte/mca/state/state.h"
#include "orte/mca/state/base/base.h"
#include "orte/mca/state/base/state_private.h"
#include "state_orted.h"
/*
* Module functions: Global
*/
static int init(void);
static int finalize(void);
/******************
* ORTED module
******************/
orte_state_base_module_t orte_state_orted_module = {
init,
finalize,
orte_state_base_activate_job_state,
orte_state_base_add_job_state,
orte_state_base_set_job_state_callback,
orte_state_base_set_job_state_priority,
orte_state_base_remove_job_state,
orte_state_base_activate_proc_state,
orte_state_base_add_proc_state,
orte_state_base_set_proc_state_callback,
orte_state_base_set_proc_state_priority,
orte_state_base_remove_proc_state
};
/* Local functions */
static void track_jobs(int fd, short argc, void *cbdata);
static void track_procs(int fd, short argc, void *cbdata);
static int pack_state_update(opal_buffer_t *buf, orte_job_t *jdata);
static int pack_child_contact_info(orte_jobid_t jobid, opal_buffer_t *buf);
/* defined default state machines */
static orte_job_state_t job_states[] = {
ORTE_JOB_STATE_LOCAL_LAUNCH_COMPLETE,
};
static orte_state_cbfunc_t job_callbacks[] = {
track_jobs
};
static orte_proc_state_t proc_states[] = {
ORTE_PROC_STATE_RUNNING,
ORTE_PROC_STATE_REGISTERED,
ORTE_PROC_STATE_IOF_COMPLETE,
ORTE_PROC_STATE_WAITPID_FIRED
};
static orte_state_cbfunc_t proc_callbacks[] = {
track_procs,
track_procs,
track_procs,
track_procs
};
/************************
* API Definitions
************************/
static int init(void)
{
int num_states, i, rc;
/* setup the state machine */
OBJ_CONSTRUCT(&orte_job_states, opal_list_t);
OBJ_CONSTRUCT(&orte_proc_states, opal_list_t);
num_states = sizeof(job_states) / sizeof(orte_job_state_t);
for (i=0; i < num_states; i++) {
if (ORTE_SUCCESS != (rc = orte_state.add_job_state(job_states[i],
job_callbacks[i],
ORTE_SYS_PRI))) {
ORTE_ERROR_LOG(rc);
}
}
/* add a default error response */
if (ORTE_SUCCESS != (rc = orte_state.add_job_state(ORTE_JOB_STATE_FORCED_EXIT,
orte_quit, ORTE_ERROR_PRI))) {
ORTE_ERROR_LOG(rc);
}
/* add a state for when we are ordered to terminate */
if (ORTE_SUCCESS != (rc = orte_state.add_job_state(ORTE_JOB_STATE_DAEMONS_TERMINATED,
orte_quit, ORTE_SYS_PRI))) {
ORTE_ERROR_LOG(rc);
}
if (5 < opal_output_get_verbosity(orte_state_base_framework.framework_output)) {
orte_state_base_print_job_state_machine();
}
/* populate the proc state machine to allow us to
* track proc lifecycle changes
*/
num_states = sizeof(proc_states) / sizeof(orte_proc_state_t);
for (i=0; i < num_states; i++) {
if (ORTE_SUCCESS != (rc = orte_state.add_proc_state(proc_states[i],
proc_callbacks[i],
ORTE_SYS_PRI))) {
ORTE_ERROR_LOG(rc);
}
}
if (5 < opal_output_get_verbosity(orte_state_base_framework.framework_output)) {
orte_state_base_print_proc_state_machine();
}
return ORTE_SUCCESS;
}
static int finalize(void)
{
opal_list_item_t *item;
/* cleanup the state machines */
while (NULL != (item = opal_list_remove_first(&orte_job_states))) {
OBJ_RELEASE(item);
}
OBJ_DESTRUCT(&orte_job_states);
while (NULL != (item = opal_list_remove_first(&orte_proc_states))) {
OBJ_RELEASE(item);
}
OBJ_DESTRUCT(&orte_proc_states);
return ORTE_SUCCESS;
}
static void track_jobs(int fd, short argc, void *cbdata)
{
orte_state_caddy_t *caddy = (orte_state_caddy_t*)cbdata;
opal_buffer_t *alert;
orte_plm_cmd_flag_t cmd;
int rc;
if (ORTE_JOB_STATE_LOCAL_LAUNCH_COMPLETE == caddy->job_state) {
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s state:orted:track_jobs sending local launch complete for job %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_JOBID_PRINT(caddy->jdata->jobid)));
/* update the HNP with all proc states for this job */
alert = OBJ_NEW(opal_buffer_t);
/* pack update state command */
cmd = ORTE_PLM_UPDATE_PROC_STATE;
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &cmd, 1, ORTE_PLM_CMD))) {
ORTE_ERROR_LOG(rc);
OBJ_RELEASE(alert);
goto cleanup;
}
/* pack the job info */
if (ORTE_SUCCESS != (rc = pack_state_update(alert, caddy->jdata))) {
ORTE_ERROR_LOG(rc);
OBJ_RELEASE(alert);
goto cleanup;
}
/* send it */
if (0 > (rc = orte_rml.send_buffer_nb(ORTE_PROC_MY_HNP, alert,
ORTE_RML_TAG_PLM,
orte_rml_send_callback, NULL))) {
ORTE_ERROR_LOG(rc);
OBJ_RELEASE(alert);
}
}
cleanup:
OBJ_RELEASE(caddy);
}
static void track_procs(int fd, short argc, void *cbdata)
{
orte_state_caddy_t *caddy = (orte_state_caddy_t*)cbdata;
orte_process_name_t *proc = &caddy->name;
orte_proc_state_t state = caddy->proc_state;
orte_job_t *jdata;
orte_proc_t *pdata, *pptr;
opal_buffer_t *alert;
int rc, i;
orte_plm_cmd_flag_t cmd;
orte_vpid_t null=ORTE_VPID_INVALID;
int8_t flag;
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s state:orted:track_procs called for proc %s state %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(proc),
orte_proc_state_to_str(state)));
/* get the job object for this proc */
if (NULL == (jdata = orte_get_job_data_object(proc->jobid))) {
ORTE_ERROR_LOG(ORTE_ERR_NOT_FOUND);
goto cleanup;
}
pdata = (orte_proc_t*)opal_pointer_array_get_item(jdata->procs, proc->vpid);
if (ORTE_PROC_STATE_RUNNING == state) {
/* update the proc state */
pdata->state = state;
jdata->num_launched++;
/* don't update until we are told that all are done */
} else if (ORTE_PROC_STATE_REGISTERED == state) {
/* update the proc state */
pdata->state = state;
jdata->num_reported++;
if (jdata->num_reported == jdata->num_local_procs) {
/* once everyone registers, send their contact info to
* the HNP so it is available to debuggers and anyone
* else that needs it
*/
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s state:orted: sending contact info to HNP",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME)));
alert = OBJ_NEW(opal_buffer_t);
/* pack init routes command */
cmd = ORTE_PLM_INIT_ROUTES_CMD;
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &cmd, 1, ORTE_PLM_CMD))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
/* pack the jobid */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &proc->jobid, 1, ORTE_JOBID))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
/* pack all the local child vpids */
for (i=0; i < orte_local_children->size; i++) {
if (NULL == (pptr = (orte_proc_t*)opal_pointer_array_get_item(orte_local_children, i))) {
continue;
}
if (pptr->name.jobid == proc->jobid) {
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &pptr->name.vpid, 1, ORTE_VPID))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
if (pptr->mpi_proc) {
flag = 1;
} else {
flag = 0;
}
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &flag, 1, OPAL_INT8))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
}
}
/* pack an invalid marker */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &null, 1, ORTE_VPID))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
/* add in contact info for all procs in the job */
if (ORTE_SUCCESS != (rc = pack_child_contact_info(proc->jobid, alert))) {
ORTE_ERROR_LOG(rc);
OBJ_DESTRUCT(&alert);
goto cleanup;
}
/* send it */
if (0 > (rc = orte_rml.send_buffer_nb(ORTE_PROC_MY_HNP, alert,
ORTE_RML_TAG_PLM,
orte_rml_send_callback, NULL))) {
ORTE_ERROR_LOG(rc);
} else {
rc = ORTE_SUCCESS;
}
}
} else if (ORTE_PROC_STATE_IOF_COMPLETE == state) {
/* do NOT update the proc state as this can hit
* while we are still trying to notify the HNP of
* successful launch for short-lived procs
*/
pdata->iof_complete = true;
if (pdata->alive && pdata->waitpid_recvd) {
/* the proc has terminated */
pdata->alive = false;
pdata->state = ORTE_PROC_STATE_TERMINATED;
/* Clean up the session directory as if we were the process
* itself. This covers the case where the process died abnormally
* and didn't cleanup its own session directory.
*/
orte_session_dir_finalize(proc);
/* track job status */
jdata->num_terminated++;
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s IOF COMPLETE FOR PROC %s NTERM %s NLOC %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&pdata->name),
ORTE_VPID_PRINT(jdata->num_terminated),
ORTE_VPID_PRINT(jdata->num_local_procs)));
if (jdata->num_terminated == jdata->num_local_procs) {
/* pack update state command */
cmd = ORTE_PLM_UPDATE_PROC_STATE;
alert = OBJ_NEW(opal_buffer_t);
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &cmd, 1, ORTE_PLM_CMD))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
/* pack the job info */
if (ORTE_SUCCESS != (rc = pack_state_update(alert, jdata))) {
ORTE_ERROR_LOG(rc);
}
/* send it */
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s SENDING JOB TERMINATION UPDATE FOR JOB %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_JOBID_PRINT(jdata->jobid)));
if (0 > (rc = orte_rml.send_buffer_nb(ORTE_PROC_MY_HNP, alert,
ORTE_RML_TAG_PLM,
orte_rml_send_callback, NULL))) {
ORTE_ERROR_LOG(rc);
}
/* if we are trying to terminate and our routes are
* gone, then terminate ourselves IF no local procs
* remain (might be some from another job)
*/
if (orte_orteds_term_ordered &&
0 == orte_routed.num_routes()) {
for (i=0; i < orte_local_children->size; i++) {
if (NULL != (pptr = (orte_proc_t*)opal_pointer_array_get_item(orte_local_children, i)) &&
pptr->alive) {
/* at least one is still alive */
goto moveon;
}
}
/* call our appropriate exit procedure */
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s orted:state: all routes and children gone - exiting",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME)));
ORTE_ACTIVATE_JOB_STATE(NULL, ORTE_JOB_STATE_DAEMONS_TERMINATED);
}
}
}
moveon:
/* Release the stdin IOF file descriptor for this child, if one
* was defined. File descriptors for the other IOF channels - stdout,
* stderr, and stddiag - were released when their associated pipes
* were cleared and closed due to termination of the process
* Do this after we handle termination in case the IOF needs
* to check to see if all procs from the job are actually terminated
*/
if (NULL != orte_iof.close) {
orte_iof.close(proc, ORTE_IOF_STDIN);
}
} else if (ORTE_PROC_STATE_WAITPID_FIRED == state) {
/* do NOT update the proc state as this can hit
* while we are still trying to notify the HNP of
* successful launch for short-lived procs
*/
pdata->waitpid_recvd = true;
if (pdata->alive && pdata->iof_complete) {
/* the proc has terminated */
pdata->alive = false;
pdata->state = ORTE_PROC_STATE_TERMINATED;
/* Clean up the session directory as if we were the process
* itself. This covers the case where the process died abnormally
* and didn't cleanup its own session directory.
*/
orte_session_dir_finalize(proc);
/* track job status */
jdata->num_terminated++;
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s WAITPID FOR PROC %s NTERM %s NLOC %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_NAME_PRINT(&pdata->name),
ORTE_VPID_PRINT(jdata->num_terminated),
ORTE_VPID_PRINT(jdata->num_local_procs)));
if (jdata->num_terminated == jdata->num_local_procs) {
/* pack update state command */
cmd = ORTE_PLM_UPDATE_PROC_STATE;
alert = OBJ_NEW(opal_buffer_t);
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &cmd, 1, ORTE_PLM_CMD))) {
ORTE_ERROR_LOG(rc);
goto cleanup;
}
/* pack the job info */
if (ORTE_SUCCESS != (rc = pack_state_update(alert, jdata))) {
ORTE_ERROR_LOG(rc);
}
/* send it */
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s SENDING PROC TERMINATION UPDATE FOR JOB %s",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME),
ORTE_JOBID_PRINT(jdata->jobid)));
if (0 > (rc = orte_rml.send_buffer_nb(ORTE_PROC_MY_HNP, alert,
ORTE_RML_TAG_PLM,
orte_rml_send_callback, NULL))) {
ORTE_ERROR_LOG(rc);
}
/* if we are trying to terminate and our routes are
* gone, then terminate ourselves IF no local procs
* remain (might be some from another job)
*/
if (orte_orteds_term_ordered &&
0 == orte_routed.num_routes()) {
for (i=0; i < orte_local_children->size; i++) {
if (NULL != (pptr = (orte_proc_t*)opal_pointer_array_get_item(orte_local_children, i)) &&
pptr->alive) {
/* at least one is still alive */
goto moveon;
}
}
/* call our appropriate exit procedure */
OPAL_OUTPUT_VERBOSE((5, orte_state_base_framework.framework_output,
"%s orted:state: all routes and children gone - exiting",
ORTE_NAME_PRINT(ORTE_PROC_MY_NAME)));
ORTE_ACTIVATE_JOB_STATE(NULL, ORTE_JOB_STATE_DAEMONS_TERMINATED);
}
}
}
}
cleanup:
OBJ_RELEASE(caddy);
}
static int pack_state_for_proc(opal_buffer_t *alert, orte_proc_t *child)
{
int rc;
/* pack the child's vpid */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &(child->name.vpid), 1, ORTE_VPID))) {
ORTE_ERROR_LOG(rc);
return rc;
}
/* pack the pid */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &child->pid, 1, OPAL_PID))) {
ORTE_ERROR_LOG(rc);
return rc;
}
/* pack its state */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &child->state, 1, ORTE_PROC_STATE))) {
ORTE_ERROR_LOG(rc);
return rc;
}
/* pack its exit code */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &child->exit_code, 1, ORTE_EXIT_CODE))) {
ORTE_ERROR_LOG(rc);
return rc;
}
return ORTE_SUCCESS;
}
static int pack_state_update(opal_buffer_t *alert, orte_job_t *jdata)
{
int i, rc;
orte_proc_t *child;
orte_vpid_t null=ORTE_VPID_INVALID;
/* pack the jobid */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &jdata->jobid, 1, ORTE_JOBID))) {
ORTE_ERROR_LOG(rc);
return rc;
}
for (i=0; i < orte_local_children->size; i++) {
if (NULL == (child = (orte_proc_t*)opal_pointer_array_get_item(orte_local_children, i))) {
continue;
}
/* if this child is part of the job... */
if (child->name.jobid == jdata->jobid) {
if (ORTE_SUCCESS != (rc = pack_state_for_proc(alert, child))) {
ORTE_ERROR_LOG(rc);
return rc;
}
}
}
/* flag that this job is complete so the receiver can know */
if (ORTE_SUCCESS != (rc = opal_dss.pack(alert, &null, 1, ORTE_VPID))) {
ORTE_ERROR_LOG(rc);
return rc;
}
return ORTE_SUCCESS;
}
static int pack_child_contact_info(orte_jobid_t jobid, opal_buffer_t *buf)
{
int i, rc;
orte_proc_t *pptr;
for (i=0; i < orte_local_children->size; i++) {
if (NULL == (pptr = (orte_proc_t*)opal_pointer_array_get_item(orte_local_children, i))) {
continue;
}
if (jobid == pptr->name.jobid) {
if (OPAL_SUCCESS != (rc = opal_dss.pack(buf, &pptr->name.vpid, 1, ORTE_VPID))) {
ORTE_ERROR_LOG(rc);
return rc;
}
if (OPAL_SUCCESS != (rc = opal_dss.pack(buf, &pptr->rml_uri, 1, OPAL_STRING))) {
ORTE_ERROR_LOG(rc);
return rc;
}
}
}
return ORTE_SUCCESS;
}
| 38.91587 | 113 | 0.541444 | [
"object"
] |
bd48e92bb074b502db024082eebeef6206389546 | 6,580 | h | C | IMU/VTK-6.2.0/Common/Core/vtkSMPThreadLocal.h | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | IMU/VTK-6.2.0/Common/Core/vtkSMPThreadLocal.h | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | IMU/VTK-6.2.0/Common/Core/vtkSMPThreadLocal.h | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: vtkSMPThreadLocal.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkSMPThreadLocal - A simple thread local implementation for sequential operations.
// .SECTION Description
// A thread local object is one that maintains a copy of an object of the
// template type for each thread that processes data. vtkSMPThreadLocal
// creates storage for all threads but the actual objects are created
// the first time Local() is called. Note that some of the vtkSMPThreadLocal
// API is not thread safe. It can be safely used in a multi-threaded
// environment because Local() returns storage specific to a particular
// thread, which by default will be accessed sequentially. It is also
// thread-safe to iterate over vtkSMPThreadLocal as long as each thread
// creates its own iterator and does not change any of the thread local
// objects.
//
// A common design pattern in using a thread local storage object is to
// write/accumulate data to local object when executing in parallel and
// then having a sequential code block that iterates over the whole storage
// using the iterators to do the final accumulation.
//
// Note that this particular implementation is designed to work in sequential
// mode and supports only 1 thread.
#ifndef vtkSMPThreadLocal_h
#define vtkSMPThreadLocal_h
#include "vtkSystemIncludes.h"
#include <vector>
template <typename T>
class vtkSMPThreadLocal
{
typedef std::vector<T> TLS;
typedef typename TLS::iterator TLSIter;
public:
// Description:
// Default constructor. Creates a default exemplar.
vtkSMPThreadLocal() : NumInitialized(0)
{
this->Initialize();
}
// Description:
// Constructor that allows the specification of an exemplar object
// which is used when constructing objects when Local() is first called.
// Note that a copy of the exemplar is created using its copy constructor.
vtkSMPThreadLocal(const T& exemplar) : NumInitialized(0), Exemplar(exemplar)
{
this->Initialize();
}
// Description:
// Returns an object of type T that is local to the current thread.
// This needs to be called mainly within a threaded execution path.
// It will create a new object (local to the tread so each thread
// get their own when calling Local) which is a copy of exemplar as passed
// to the constructor (or a default object if no exemplar was provided)
// the first time it is called. After the first time, it will return
// the same object.
T& Local()
{
int tid = this->GetThreadID();
if (!this->Initialized[tid])
{
this->Internal[tid] = this->Exemplar;
this->Initialized[tid] = true;
++this->NumInitialized;
}
return this->Internal[tid];
}
// Description:
// Return the number of thread local objects that have been initialized
size_t size() const
{
return this->NumInitialized;
}
// Description:
// Subset of the standard iterator API.
// The most common design pattern is to use iterators in a sequential
// code block and to use only the thread local objects in parallel
// code blocks.
// It is thread safe to iterate over the thread local containers
// as long as each thread uses its own iterator and does not modify
// objects in the container.
class iterator
{
public:
iterator& operator++()
{
this->InitIter++;
this->Iter++;
// Make sure to skip uninitialized
// entries.
while(this->InitIter != this->EndIter)
{
if (*this->InitIter)
{
break;
}
this->InitIter++;
this->Iter++;
}
return *this;
}
iterator operator++(int)
{
iterator copy = *this;
++(*this);
return copy;
}
bool operator==(const iterator& other)
{
return this->Iter == other.Iter;
}
bool operator!=(const iterator& other)
{
return this->Iter != other.Iter;
}
T& operator*()
{
return *this->Iter;
}
T* operator->()
{
return &*this->Iter;
}
private:
friend class vtkSMPThreadLocal<T>;
std::vector<bool>::iterator InitIter;
std::vector<bool>::iterator EndIter;
TLSIter Iter;
};
// Description:
// Returns a new iterator pointing to the beginning of
// the local storage container. Thread safe.
iterator begin()
{
TLSIter iter = this->Internal.begin();
std::vector<bool>::iterator iter2 =
this->Initialized.begin();
std::vector<bool>::iterator enditer =
this->Initialized.end();
// fast forward to first initialized
// value
while(iter2 != enditer)
{
if (*iter2)
{
break;
}
iter2++;
iter++;
}
iterator retVal;
retVal.InitIter = iter2;
retVal.EndIter = enditer;
retVal.Iter = iter;
return retVal;
};
// Description:
// Returns a new iterator pointing to past the end of
// the local storage container. Thread safe.
iterator end()
{
iterator retVal;
retVal.InitIter = this->Initialized.end();
retVal.EndIter = this->Initialized.end();
retVal.Iter = this->Internal.end();
return retVal;
}
private:
TLS Internal;
std::vector<bool> Initialized;
size_t NumInitialized;
T Exemplar;
void Initialize()
{
this->Internal.resize(this->GetNumberOfThreads());
this->Initialized.resize(this->GetNumberOfThreads());
std::fill(this->Initialized.begin(),
this->Initialized.end(),
false);
}
inline int GetNumberOfThreads()
{
return 1;
}
inline int GetThreadID()
{
return 0;
}
};
#endif
// VTK-HeaderTest-Exclude: vtkSMPThreadLocal.h
| 29.506726 | 93 | 0.611854 | [
"object",
"vector"
] |
bd4e69183a56313fae2d9bfc206fc1346caedb0f | 9,716 | c | C | release/src/linux/linux/fs/read_write.c | enfoTek/tomato.linksys.e2000.nvram-mod | 2ce3a5217def49d6df7348522e2bfda702b56029 | [
"FSFAP"
] | 80 | 2015-01-02T10:14:04.000Z | 2021-06-07T06:29:49.000Z | release/src/linux/linux/fs/read_write.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 9 | 2015-05-14T11:03:12.000Z | 2018-01-04T07:12:58.000Z | release/src/linux/linux/fs/read_write.c | unforgiven512/tomato | 96f09fab4929c6ddde5c9113f1b2476ad37133c4 | [
"FSFAP"
] | 69 | 2015-01-02T10:45:56.000Z | 2021-09-06T07:52:13.000Z | /*
* linux/fs/read_write.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Minor pieces Copyright (C) 2002 Red Hat Inc, All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/file.h>
#include <linux/uio.h>
#include <linux/smp_lock.h>
#include <linux/dnotify.h>
#include <asm/uaccess.h>
struct file_operations generic_ro_fops = {
llseek: generic_file_llseek,
read: generic_file_read,
mmap: generic_file_mmap,
};
ssize_t generic_read_dir(struct file *filp, char *buf, size_t siz, loff_t *ppos)
{
return -EISDIR;
}
loff_t generic_file_llseek(struct file *file, loff_t offset, int origin)
{
long long retval;
switch (origin) {
case 2:
offset += file->f_dentry->d_inode->i_size;
break;
case 1:
offset += file->f_pos;
}
retval = -EINVAL;
if (offset>=0 && offset<=file->f_dentry->d_inode->i_sb->s_maxbytes) {
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_reada = 0;
file->f_version = ++event;
}
retval = offset;
}
return retval;
}
loff_t no_llseek(struct file *file, loff_t offset, int origin)
{
return -ESPIPE;
}
loff_t default_llseek(struct file *file, loff_t offset, int origin)
{
long long retval;
switch (origin) {
case 2:
offset += file->f_dentry->d_inode->i_size;
break;
case 1:
offset += file->f_pos;
}
retval = -EINVAL;
if (offset >= 0) {
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_reada = 0;
file->f_version = ++event;
}
retval = offset;
}
return retval;
}
static inline loff_t llseek(struct file *file, loff_t offset, int origin)
{
loff_t (*fn)(struct file *, loff_t, int);
loff_t retval;
fn = default_llseek;
if (file->f_op && file->f_op->llseek)
fn = file->f_op->llseek;
lock_kernel();
retval = fn(file, offset, origin);
unlock_kernel();
return retval;
}
asmlinkage off_t sys_lseek(unsigned int fd, off_t offset, unsigned int origin)
{
off_t retval;
struct file * file;
retval = -EBADF;
file = fget(fd);
if (!file)
goto bad;
retval = -EINVAL;
if (origin <= 2) {
loff_t res = llseek(file, offset, origin);
retval = res;
if (res != (loff_t)retval)
retval = -EOVERFLOW; /* LFS: should only happen on 32 bit platforms */
}
fput(file);
bad:
return retval;
}
#if !defined(__alpha__)
asmlinkage long sys_llseek(unsigned int fd, unsigned long offset_high,
unsigned long offset_low, loff_t * result,
unsigned int origin)
{
int retval;
struct file * file;
loff_t offset;
retval = -EBADF;
file = fget(fd);
if (!file)
goto bad;
retval = -EINVAL;
if (origin > 2)
goto out_putf;
offset = llseek(file, ((loff_t) offset_high << 32) | offset_low,
origin);
retval = (int)offset;
if (offset >= 0) {
retval = -EFAULT;
if (!copy_to_user(result, &offset, sizeof(offset)))
retval = 0;
}
out_putf:
fput(file);
bad:
return retval;
}
#endif
asmlinkage ssize_t sys_read(unsigned int fd, char * buf, size_t count)
{
ssize_t ret;
struct file * file;
ret = -EBADF;
file = fget(fd);
if (file) {
if (file->f_mode & FMODE_READ) {
ret = locks_verify_area(FLOCK_VERIFY_READ, file->f_dentry->d_inode,
file, file->f_pos, count);
if (!ret) {
ssize_t (*read)(struct file *, char *, size_t, loff_t *);
ret = -EINVAL;
if (file->f_op && (read = file->f_op->read) != NULL)
ret = read(file, buf, count, &file->f_pos);
}
}
if (ret > 0)
dnotify_parent(file->f_dentry, DN_ACCESS);
fput(file);
}
return ret;
}
asmlinkage ssize_t sys_write(unsigned int fd, const char * buf, size_t count)
{
ssize_t ret;
struct file * file;
ret = -EBADF;
file = fget(fd);
if (file) {
if (file->f_mode & FMODE_WRITE) {
struct inode *inode = file->f_dentry->d_inode;
ret = locks_verify_area(FLOCK_VERIFY_WRITE, inode, file,
file->f_pos, count);
if (!ret) {
ssize_t (*write)(struct file *, const char *, size_t, loff_t *);
ret = -EINVAL;
if (file->f_op && (write = file->f_op->write) != NULL)
ret = write(file, buf, count, &file->f_pos);
}
}
if (ret > 0)
dnotify_parent(file->f_dentry, DN_MODIFY);
fput(file);
}
return ret;
}
static ssize_t do_readv_writev(int type, struct file *file,
const struct iovec * vector,
unsigned long count)
{
typedef ssize_t (*io_fn_t)(struct file *, char *, size_t, loff_t *);
typedef ssize_t (*iov_fn_t)(struct file *, const struct iovec *, unsigned long, loff_t *);
ssize_t tot_len;
struct iovec iovstack[UIO_FASTIOV];
struct iovec *iov=iovstack;
ssize_t ret, i;
io_fn_t fn;
iov_fn_t fnv;
struct inode *inode;
/*
* First get the "struct iovec" from user memory and
* verify all the pointers
*/
ret = 0;
if (!count)
goto out_nofree;
ret = -EINVAL;
if (count > UIO_MAXIOV)
goto out_nofree;
if (!file->f_op)
goto out_nofree;
if (count > UIO_FASTIOV) {
ret = -ENOMEM;
iov = kmalloc(count*sizeof(struct iovec), GFP_KERNEL);
if (!iov)
goto out_nofree;
}
ret = -EFAULT;
if (copy_from_user(iov, vector, count*sizeof(*vector)))
goto out;
/*
* Single unix specification:
* We should -EINVAL if an element length is not >= 0 and fitting an ssize_t
* The total length is fitting an ssize_t
*
* Be careful here because iov_len is a size_t not an ssize_t
*/
tot_len = 0;
ret = -EINVAL;
for (i = 0 ; i < count ; i++) {
ssize_t tmp = tot_len;
ssize_t len = (ssize_t) iov[i].iov_len;
if (len < 0) /* size_t not fitting an ssize_t .. */
goto out;
tot_len += len;
if (tot_len < tmp) /* maths overflow on the ssize_t */
goto out;
}
inode = file->f_dentry->d_inode;
/* VERIFY_WRITE actually means a read, as we write to user space */
ret = locks_verify_area((type == VERIFY_WRITE
? FLOCK_VERIFY_READ : FLOCK_VERIFY_WRITE),
inode, file, file->f_pos, tot_len);
if (ret) goto out;
fnv = (type == VERIFY_WRITE ? file->f_op->readv : file->f_op->writev);
if (fnv) {
ret = fnv(file, iov, count, &file->f_pos);
goto out;
}
/* VERIFY_WRITE actually means a read, as we write to user space */
fn = (type == VERIFY_WRITE ? file->f_op->read :
(io_fn_t) file->f_op->write);
ret = 0;
vector = iov;
while (count > 0) {
void * base;
size_t len;
ssize_t nr;
base = vector->iov_base;
len = vector->iov_len;
vector++;
count--;
nr = fn(file, base, len, &file->f_pos);
if (nr < 0) {
if (!ret) ret = nr;
break;
}
ret += nr;
if (nr != len)
break;
}
out:
if (iov != iovstack)
kfree(iov);
out_nofree:
/* VERIFY_WRITE actually means a read, as we write to user space */
if ((ret + (type == VERIFY_WRITE)) > 0)
dnotify_parent(file->f_dentry,
(type == VERIFY_WRITE) ? DN_MODIFY : DN_ACCESS);
return ret;
}
asmlinkage ssize_t sys_readv(unsigned long fd, const struct iovec * vector,
unsigned long count)
{
struct file * file;
ssize_t ret;
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (file->f_op && (file->f_mode & FMODE_READ) &&
(file->f_op->readv || file->f_op->read))
ret = do_readv_writev(VERIFY_WRITE, file, vector, count);
fput(file);
bad_file:
return ret;
}
asmlinkage ssize_t sys_writev(unsigned long fd, const struct iovec * vector,
unsigned long count)
{
struct file * file;
ssize_t ret;
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (file->f_op && (file->f_mode & FMODE_WRITE) &&
(file->f_op->writev || file->f_op->write))
ret = do_readv_writev(VERIFY_READ, file, vector, count);
fput(file);
bad_file:
return ret;
}
/* From the Single Unix Spec: pread & pwrite act like lseek to pos + op +
lseek back to original location. They fail just like lseek does on
non-seekable files. */
asmlinkage ssize_t sys_pread(unsigned int fd, char * buf,
size_t count, loff_t pos)
{
ssize_t ret;
struct file * file;
ssize_t (*read)(struct file *, char *, size_t, loff_t *);
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (!(file->f_mode & FMODE_READ))
goto out;
ret = locks_verify_area(FLOCK_VERIFY_READ, file->f_dentry->d_inode,
file, pos, count);
if (ret)
goto out;
ret = -EINVAL;
if (!file->f_op || !(read = file->f_op->read))
goto out;
if (pos < 0)
goto out;
ret = read(file, buf, count, &pos);
if (ret > 0)
dnotify_parent(file->f_dentry, DN_ACCESS);
out:
fput(file);
bad_file:
return ret;
}
asmlinkage ssize_t sys_pwrite(unsigned int fd, const char * buf,
size_t count, loff_t pos)
{
ssize_t ret;
struct file * file;
ssize_t (*write)(struct file *, const char *, size_t, loff_t *);
ret = -EBADF;
file = fget(fd);
if (!file)
goto bad_file;
if (!(file->f_mode & FMODE_WRITE))
goto out;
ret = locks_verify_area(FLOCK_VERIFY_WRITE, file->f_dentry->d_inode,
file, pos, count);
if (ret)
goto out;
ret = -EINVAL;
if (!file->f_op || !(write = file->f_op->write))
goto out;
if (pos < 0)
goto out;
ret = write(file, buf, count, &pos);
if (ret > 0)
dnotify_parent(file->f_dentry, DN_MODIFY);
out:
fput(file);
bad_file:
return ret;
}
| 22.700935 | 91 | 0.65459 | [
"vector"
] |
bd4faae0dcdfe8aa1b59759f2ec07c4767bdd8ee | 1,896 | h | C | Kernel/Formats/caspsr/dsp/CASPSRUnpacker.h | rwharton/dspsr_dsn | 135cc86c43931311424beeb5a459ba570f1f83f7 | [
"AFL-2.1"
] | null | null | null | Kernel/Formats/caspsr/dsp/CASPSRUnpacker.h | rwharton/dspsr_dsn | 135cc86c43931311424beeb5a459ba570f1f83f7 | [
"AFL-2.1"
] | null | null | null | Kernel/Formats/caspsr/dsp/CASPSRUnpacker.h | rwharton/dspsr_dsn | 135cc86c43931311424beeb5a459ba570f1f83f7 | [
"AFL-2.1"
] | null | null | null | /*
*/
#ifndef __dsp_CASPSRUnpacker_h
#define __dsp_CASPSRUnpacker_h
#include "dsp/EightBitUnpacker.h"
#include "ThreadContext.h"
namespace dsp {
class CASPSRUnpacker : public HistUnpacker
{
public:
//! Constructor
CASPSRUnpacker (const char* name = "CASPSRUnpacker");
~CASPSRUnpacker ();
//! Cloner (calls new)
virtual CASPSRUnpacker * clone () const;
//! Return true if the unpacker can operate on the specified device
bool get_device_supported (Memory*) const;
//! Set the device on which the unpacker will operate
void set_device (Memory*);
protected:
Reference::To<BitTable> table;
//! Return true if we can convert the Observation
bool matches (const Observation* observation);
void unpack ();
void unpack (uint64_t ndat, const unsigned char* from,
float* into, const unsigned fskip,
unsigned long* hist);
void * gpu_stream;
void unpack_on_gpu ();
unsigned get_resolution ()const ;
private:
ThreadContext * context;
unsigned n_threads;
unsigned thread_count;
bool device_prepared;
bool single_thread;
void unpack_single_thread ();
//! cpu_unpacker_thread ids
std::vector <pthread_t> ids;
//! Signals the CPU threads to start
void start_threads ();
//! Waits for the CPU threads to complete
void wait_threads ();
//! Stops the CPU threads
void stop_threads ();
//! Joins the CPU threads
void join_threads ();
//! sk_thread calls thread method
static void* cpu_unpacker_thread (void*);
//! The CPU CASPSR Unpacker thread
void thread ();
enum State { Idle, Active, Quit };
//! overall state
State state;
//! sk_thread states
std::vector <State> states;
//! maximum number of GPU threads per block
int threadsPerBlock;
};
}
#endif
| 19.151515 | 71 | 0.653481 | [
"vector"
] |
bd653bcfd150f156bd234bf8a3264bb27da86c1f | 1,817 | h | C | chrome/browser/enterprise/reporting/browser_report_generator_android.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/enterprise/reporting/browser_report_generator_android.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | chrome/browser/enterprise/reporting/browser_report_generator_android.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ENTERPRISE_REPORTING_BROWSER_REPORT_GENERATOR_ANDROID_H_
#define CHROME_BROWSER_ENTERPRISE_REPORTING_BROWSER_REPORT_GENERATOR_ANDROID_H_
#include <memory>
#include <string>
#include "base/callback_forward.h"
#include "components/enterprise/browser/reporting/browser_report_generator.h"
namespace enterprise_management {
class BrowserReport;
} // namespace enterprise_management
namespace enterprise_reporting {
// Android implementation of platform-specific info fetching for Enterprise
// browser report generation.
class BrowserReportGeneratorAndroid : public BrowserReportGenerator::Delegate {
public:
using ReportCallback = base::OnceCallback<void(
std::unique_ptr<enterprise_management::BrowserReport>)>;
BrowserReportGeneratorAndroid();
BrowserReportGeneratorAndroid(const BrowserReportGeneratorAndroid&) = delete;
BrowserReportGeneratorAndroid& operator=(
const BrowserReportGeneratorAndroid&) = delete;
~BrowserReportGeneratorAndroid() override;
// BrowserReportGenerator::Delegate implementation
std::string GetExecutablePath() override;
version_info::Channel GetChannel() override;
std::vector<BrowserReportGenerator::ReportedProfileData> GetReportedProfiles()
override;
bool IsExtendedStableChannel() override;
void GenerateBuildStateInfo(
enterprise_management::BrowserReport* report) override;
void GeneratePluginsIfNeeded(
ReportCallback callback,
std::unique_ptr<enterprise_management::BrowserReport> report) override;
};
} // namespace enterprise_reporting
#endif // CHROME_BROWSER_ENTERPRISE_REPORTING_BROWSER_REPORT_GENERATOR_ANDROID_H_
| 37.081633 | 82 | 0.817281 | [
"vector"
] |
bd6602a58307d57bd263b78c9975ad2ecf0d359e | 1,677 | h | C | rela/model_locker.h | facebookresearch/rela | 0bd091576921b8f060b73159f8393a8e13aa6227 | [
"MIT"
] | 93 | 2019-10-25T20:10:47.000Z | 2022-03-14T15:28:57.000Z | rela/model_locker.h | facebookresearch/rela | 0bd091576921b8f060b73159f8393a8e13aa6227 | [
"MIT"
] | 1 | 2020-05-16T08:18:46.000Z | 2020-05-16T08:18:46.000Z | rela/model_locker.h | facebookresearch/rela | 0bd091576921b8f060b73159f8393a8e13aa6227 | [
"MIT"
] | 10 | 2019-11-29T23:48:10.000Z | 2022-03-24T07:42:22.000Z | // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
#pragma once
#include <pybind11/pybind11.h>
#include "rela/types.h"
namespace rela {
class ModelLocker {
public:
ModelLocker(std::vector<py::object> pyModels, const std::string& device)
: device(torch::Device(device))
, pyModels_(pyModels)
, modelCallCounts_(pyModels.size(), 0)
, latestModel_(0) {
// assert(pyModels_.size() > 1);
for (size_t i = 0; i < pyModels_.size(); ++i) {
models_.push_back(pyModels_[i].attr("_c").cast<TorchJitModel*>());
// modelCallCounts_.push_back(0);
}
}
void updateModel(py::object pyModel) {
std::unique_lock<std::mutex> lk(m_);
int id = (latestModel_ + 1) % modelCallCounts_.size();
cv_.wait(lk, [this, id] { return modelCallCounts_[id] == 0; });
lk.unlock();
pyModels_[id].attr("load_state_dict")(pyModel.attr("state_dict")());
lk.lock();
latestModel_ = id;
lk.unlock();
}
const TorchJitModel getModel(int* id) {
std::lock_guard<std::mutex> lk(m_);
*id = latestModel_;
// std::cout << "using mdoel: " << latestModel_ << std::endl;
++modelCallCounts_[latestModel_];
return *models_[latestModel_];
}
void releaseModel(int id) {
std::unique_lock<std::mutex> lk(m_);
--modelCallCounts_[id];
if (modelCallCounts_[id] == 0) {
cv_.notify_one();
}
}
const torch::Device device;
private:
// py::function model_cons_;
std::vector<py::object> pyModels_;
std::vector<int> modelCallCounts_;
int latestModel_;
std::vector<TorchJitModel*> models_;
std::mutex m_;
std::condition_variable cv_;
};
} // namespace rela
| 24.661765 | 74 | 0.639833 | [
"object",
"vector"
] |
bd669a9e23110b2675d05a2693dfc5c8ccc7fbf6 | 840 | h | C | 3D Basics/IntroScene.h | Csumbavamba/Terrain-Generation | 8a3d86494d5ce0f9a0294210aba8464edabc57da | [
"MIT"
] | null | null | null | 3D Basics/IntroScene.h | Csumbavamba/Terrain-Generation | 8a3d86494d5ce0f9a0294210aba8464edabc57da | [
"MIT"
] | null | null | null | 3D Basics/IntroScene.h | Csumbavamba/Terrain-Generation | 8a3d86494d5ce0f9a0294210aba8464edabc57da | [
"MIT"
] | null | null | null | #pragma once
#include "Scene.h"
#include "Dependencies\soil\SOIL.h"
#include "Dependencies\glew\glew.h"
#include "Dependencies\freeglut\freeglut.h"
#include "glm.hpp"
#include "gtc/matrix_transform.hpp"
#include "gtc/type_ptr.hpp"
#include "Mesh2D_Quad.h"
#include "Texture.h"
#include "Transform.h"
#include "Camera.h"
#include "glm.hpp"
#include "gtc/matrix_transform.hpp"
#include "gtc/type_ptr.hpp"
#include "GameObject.h"
#include "Input.h"
#include <iostream>
class IntroScene :public Scene
{
Texture texture;
public:
IntroScene();
virtual ~IntroScene();
virtual void Render(GLuint program) override;
virtual void Update(float deltaTime) override;
virtual void Initialise() override;
void updateSprite();
private:
bool hasBeenReleased = true;
int frameIndex = 1;
int animationIndex = 13;
bool isVisible = true;
};
| 20 | 47 | 0.746429 | [
"render",
"transform"
] |
bd6d1ba460ae0b89ed595a7fc6af23d370cc555a | 2,234 | h | C | examples/maxpipo/PiPoGain.h | Ircam-RnD/pipo-sdk | 9d9605b1f017cb84f3bc4d50f4f82ecf29281a5d | [
"BSD-3-Clause",
"Unlicense"
] | 29 | 2016-04-19T20:43:18.000Z | 2021-05-29T03:51:26.000Z | examples/maxpipo/PiPoGain.h | ircam-ismm/pipo-sdk | 9d9605b1f017cb84f3bc4d50f4f82ecf29281a5d | [
"BSD-3-Clause",
"Unlicense"
] | 5 | 2017-11-07T15:44:29.000Z | 2017-11-15T15:39:25.000Z | examples/maxpipo/PiPoGain.h | ircam-ismm/pipo-sdk | 9d9605b1f017cb84f3bc4d50f4f82ecf29281a5d | [
"BSD-3-Clause",
"Unlicense"
] | 6 | 2016-05-10T12:20:14.000Z | 2021-01-17T18:39:51.000Z | /**
*
* @file PiPoGain.h
* @author Diemo.Schwarz@ircam.fr
*
* @brief PiPo gain data stream
*
* Copyright (C) 2012-2014 by IRCAM – Centre Pompidou, Paris, France.
* All rights reserved.
*
*/
#ifndef _PIPO_GAIN_
#define _PIPO_GAIN_
#include "PiPo.h"
class PiPoGain : public PiPo
{
private:
std::vector<PiPoValue> buffer_;
unsigned int framesize_; // cache max frame size
public:
PiPoScalarAttr<double> factor_attr_;
PiPoGain (Parent *parent, PiPo *receiver = NULL)
: PiPo(parent, receiver),
factor_attr_(this, "factor", "Gain Factor", false, 1.0)
{ }
~PiPoGain (void)
{ }
/* Configure PiPo module according to the input stream attributes and propagate output stream attributes.
* Note: For audio input, one PiPo frame corresponds to one sample frame, i.e. width is the number of channels, height is 1, maxFrames is the maximum number of (sample) frames passed to the module, rate is the sample rate, and domain is 1 / sample rate.
*/
int streamAttributes (bool hasTimeTags, double rate, double offset,
unsigned int width, unsigned int height,
const char **labels, bool hasVarSize,
double domain, unsigned int maxFrames)
{
// we need to store the max frame size in case hasVarSize is true
framesize_ = width * height;
// A general pipo can not work in place, we need to create an output buffer
buffer_.resize(framesize_ * maxFrames);
// we will produce the same stream layout as the input
return propagateStreamAttributes(hasTimeTags, rate, offset, width, height,
labels, hasVarSize, domain, maxFrames);
}
int frames (double time, double weight, PiPoValue *values,
unsigned int size, unsigned int num)
{
double f = factor_attr_.get(); // get gain factor here, as it could change while running
PiPoValue *outptr = &buffer_[0];
for (unsigned int i = 0; i < num; i++)
{
for (unsigned int j = 0; j < size; j++)
outptr[j] = values[j] * f;
outptr += framesize_;
values += framesize_;
}
return propagateFrames(time, weight, &buffer_[0], size, num);
}
};
#endif
| 30.60274 | 255 | 0.645031 | [
"vector"
] |
bd6d646f4026b44471e03de937a71e1a166db739 | 988 | h | C | include/sp2/collision/3d/mesh.h | daid/SeriousProton2 | 6cc9c2291ea63ffc82427ed82f51a84611f7f45c | [
"MIT"
] | 8 | 2018-01-26T20:21:08.000Z | 2021-08-30T20:28:43.000Z | include/sp2/collision/3d/mesh.h | daid/SeriousProton2 | 6cc9c2291ea63ffc82427ed82f51a84611f7f45c | [
"MIT"
] | 7 | 2018-10-28T14:52:25.000Z | 2020-12-28T19:59:04.000Z | include/sp2/collision/3d/mesh.h | daid/SeriousProton2 | 6cc9c2291ea63ffc82427ed82f51a84611f7f45c | [
"MIT"
] | 7 | 2017-05-27T16:33:37.000Z | 2022-02-18T14:07:17.000Z | #ifndef SP2_COLLISION_3D_MESH_H
#define SP2_COLLISION_3D_MESH_H
#include <vector>
#include <sp2/collision/3d/shape.h>
#include <sp2/math/vector3.h>
class btTriangleIndexVertexArray;
namespace sp {
namespace collision {
/**
NOTE: Unlike the other collision objects, the Mesh3D needs to remain in memory as long as any object is using this as collision shape.
else you will get a crash from the collision engine, as it will try to access the stored vertices/indices.
*/
class Mesh3D : public Shape3D
{
public:
#ifdef BT_USE_DOUBLE_PRECISION
using Vector3 = Vector3d;
#else
using Vector3 = Vector3f;
#endif
Mesh3D(std::vector<Vector3>&& vertices, std::vector<int>&& indices);
private:
virtual btCollisionShape* createShape() const override;
btTriangleIndexVertexArray* triangle_index_array = nullptr;
std::vector<Vector3> vertices;
std::vector<int> indices;
};
}//namespace collision
}//namespace sp
#endif//SP2_COLLISION_3D_MESH_H
| 24.097561 | 138 | 0.744939 | [
"object",
"shape",
"vector",
"3d"
] |
bd6f9e48e1ebe77598af272c59025eb926dcf5f4 | 5,140 | h | C | Engine/Src/SFEngine/Net/SFNetSystem_WinIOCP.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFEngine/Net/SFNetSystem_WinIOCP.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFEngine/Net/SFNetSystem_WinIOCP.h | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2016 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Network system for IOCP
//
//
////////////////////////////////////////////////////////////////////////////////
#pragma once
#if SF_PLATFORM == SF_PLATFORM_WINDOWS
#include "SFTypedefs.h"
#include "Net/SFNetDef.h"
#include "Net/SFNetConst.h"
namespace SF {
namespace Net {
class Connection;
enum class IOBUFFER_OPERATION : uint8_t;
////////////////////////////////////////////////////////////////////////////////
//
// Overlapped I/O structures
//
struct IOBUFFER : public WSAOVERLAPPED
{
IOBUFFER_OPERATION Operation;
// Clear Buffer
void ClearBuffer();
} ;
// UDP/TCP read/write overlapped base
struct IOBUFFER_RWBASE : public IOBUFFER
{
// IOCP buffer
WSABUF wsaBuff;
// Transferred buffer size
uint32_t TransferredSize;
union {
// UDP Read from
struct sockaddr_storage From;
struct sockaddr_storage To;
} NetAddr;
// Constructor
IOBUFFER_RWBASE();
} ;
// UDP/TCP write overlapped
struct IOBUFFER_WRITE : public IOBUFFER_RWBASE
{
// Message pointer to send
SharedPointerAtomicT<Message::MessageData> pMsgs;
// Message buffer pointer to send
uint8_t *pSendBuff;
// Constructor
IOBUFFER_WRITE();
~IOBUFFER_WRITE();
// Initialize for IO
inline void InitForIO(SF_SOCKET sockWrite);
inline void InitMsg(SharedPointerT<Message::MessageData>&& pMsg );
inline void InitBuff( uint uiBuffSize, uint8_t* pBuff );
// Setup sending mode
inline void SetupSendUDP(SF_SOCKET sockWrite, const sockaddr_storage& to, SharedPointerT<Message::MessageData>&& pMsg );
inline void SetupSendUDP(SF_SOCKET sockWrite, const sockaddr_storage& to, uint uiBuffSize, uint8_t* pBuff );
inline void SetupSendTCP(SharedPointerT<Message::MessageData>&& pMsg );
inline void SetupSendTCP( uint uiBuffSize, uint8_t* pBuff );
};
// UDP/TCP read overlapped
struct IOBUFFER_READ : public IOBUFFER_RWBASE
{
// Read flag
DWORD dwFlags;
DWORD dwNumberOfByte;
// UDP Recv socket length
INT iSockLen;
// Recv connection ID for error check
uint64_t CID;
// Recv buffer
char buffer[Const::INTER_PACKET_SIZE_MAX];
// Mark whether this buffer is in use
std::atomic<bool> bIsPending;
//CallStackTrace PendingTrace;
// constructor
IOBUFFER_READ();
~IOBUFFER_READ();
// Initialize for IO
inline void InitForIO();
inline void InitRecv( uint64_t iCID );
// Setup receiving mode
inline void SetupRecvUDP( uint64_t iCID );
inline void SetupRecvTCP( uint64_t iCID );
bool IsPendingTrue() { return bIsPending.load(std::memory_order_consume); }
Result SetPendingTrue();
Result SetPendingFalse();
};
// TCP accept overlapped
struct IOBUFFER_ACCEPT : public IOBUFFER
{
//Connection *pConnection;
SF_SOCKET sockAccept;
uint8_t pAcceptInfo[sizeof(sockaddr_storage)*2];
DWORD dwByteReceived;
// Constructor
IOBUFFER_ACCEPT();
~IOBUFFER_ACCEPT();
// Setup accept
inline void SetupAccept(SF_SOCKET sock );
} ;
////////////////////////////////////////////////////////////////////////////////
//
// IO operations
//
namespace IOCPSystem
{
////////////////////////////////////////////////////////////////////////////////
//
// IOCP thread worker
//
class IOCPWorker : public Thread
{
private:
// IOCP handle
HANDLE m_hIOCP;
public:
// Constructor/destructor
IOCPWorker();
~IOCPWorker();
inline void SetIOCPHandle( HANDLE hIOCP );
virtual void Run() override;
};
//////////////////////////////////////////////////////////////////
//
// network IOCP System
//
class IOCPSystem : public NetSystemService::NetIOSystem
{
private:
// IOCP system open reference count
SyncCounter m_RefCount;
// IOCP worker thread list
std::vector<IOCPWorker*> m_pWorkers;
// global statistic
SyncCounter m_NumReadWait;
SyncCounter m_NumWriteWait;
IHeap& m_Heap;
public:
IOCPSystem(IHeap& memoryManager);
~IOCPSystem();
IHeap& GetHeap() { return m_Heap; }
virtual Result Initialize(uint netThreadCount) override;
virtual void Terminate() override;
//virtual Result MakeSocketNonBlocking(SF_SOCKET sfd) { return ResultCode::FAIL; }
//virtual Net::WriteBufferQueue* GetWriteBufferQueue() { return nullptr; }
//// Register the socket to KQUEUE
//virtual Result RegisterToNETIO(SocketType sockType, Net::SocketIO* cbInstance) { return ResultCode::FAIL; }
//virtual Result UnregisterFromNETIO(Net::SocketIO* cbInstance) { return ResultCode::FAIL; }
//virtual const char* EventFlagToString(int32_t bufferSize, char* stringBuffer, uint32_t eventFlags) { return ""; }
};
}; // namespace IOCPSystem
#include "SFNetSystem_WinIOCP.inl"
} // namespace Net
} // namespace SF
#endif
| 21.687764 | 123 | 0.610506 | [
"vector"
] |
bd74648813ab53b1bff8ab01b3bf8a1a656a2647 | 1,354 | h | C | SWIG_CGAL/Box_intersection_d/Callbacks.h | chrisidefix/cgal-bindings | ddd8551f1ded7354c82a9690c06fcbc6512b6604 | [
"BSL-1.0"
] | 33 | 2015-04-14T22:03:37.000Z | 2022-01-23T00:01:23.000Z | SWIG_CGAL/Box_intersection_d/Callbacks.h | chrisidefix/cgal-bindings | ddd8551f1ded7354c82a9690c06fcbc6512b6604 | [
"BSL-1.0"
] | 4 | 2017-07-23T18:02:32.000Z | 2020-02-17T18:31:37.000Z | SWIG_CGAL/Box_intersection_d/Callbacks.h | chrisidefix/cgal-bindings | ddd8551f1ded7354c82a9690c06fcbc6512b6604 | [
"BSL-1.0"
] | 6 | 2015-06-10T10:51:11.000Z | 2019-04-16T10:24:53.000Z | // ------------------------------------------------------------------------------
// Copyright (c) 2014 GeometryFactory (FRANCE)
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// ------------------------------------------------------------------------------
#ifndef SWIG_CGAL_BOX_INTERSECTION_D_CALLBACKS_H
#define SWIG_CGAL_BOX_INTERSECTION_D_CALLBACKS_H
#include <vector>
#include <boost/shared_ptr.hpp>
#include <utility>
#include <SWIG_CGAL/Common/Iterator.h>
// the template parameter is not needed but in java to avoid a type erasure issue with generics
template <int DIM>
struct Collect_ids_callback{
typedef std::pair<int, int> Pair_of_int;
typedef SWIG_CGAL_Iterator<std::vector< Pair_of_int >::iterator,Pair_of_int> Ids_iterator;
#ifndef SWIG
boost::shared_ptr< std::vector< Pair_of_int > > ids_ptr;
Collect_ids_callback():ids_ptr(new std::vector< Pair_of_int >()){}
template <class Box>
void operator()( const Box& b1, const Box& b2)
{
ids_ptr->push_back( Pair_of_int(b1.id(), b2.id()) );
}
#endif
SWIG_CGAL_Iterator<std::vector< std::pair<int, int> >::iterator,std::pair<int, int> >
ids(){ return Ids_iterator(ids_ptr->begin(), ids_ptr->end()); }
};
#endif //SWIG_CGAL_BOX_INTERSECTION_D_CALLBACKS_H
| 37.611111 | 95 | 0.657312 | [
"vector"
] |
bd77f9b5453b2acbd89de3b66aca7af62c4e7cf2 | 51,236 | c | C | wb/wb_control.c | crispy-computing-machine/Winbinder | 2cba09dec0c85a14ef1d95f0f02d6df17faf6470 | [
"BSD-3-Clause"
] | 5 | 2019-12-22T03:36:53.000Z | 2022-03-31T15:33:35.000Z | wb/wb_control.c | crispy-computing-machine/Winbinder | 2cba09dec0c85a14ef1d95f0f02d6df17faf6470 | [
"BSD-3-Clause"
] | 86 | 2019-11-03T12:11:42.000Z | 2021-06-30T18:36:41.000Z | wb/wb_control.c | crispy-computing-machine/Winbinder | 2cba09dec0c85a14ef1d95f0f02d6df17faf6470 | [
"BSD-3-Clause"
] | 1 | 2022-02-16T08:26:48.000Z | 2022-02-16T08:26:48.000Z | /*******************************************************************************
WINBINDER - The native Windows binding for PHP
Copyright Hypervisual - see LICENSE.TXT for details
Author: Rubem Pechansky (http://winbinder.org/contact.php)
Functions for Windows controls
*******************************************************************************/
//----------------------------------------------------------------- DEPENDENCIES
#include "wb.h"
#include <time.h> // For time_t
#include <stdlib.h> // For itoa(), atoi()
#include <shellapi.h> // For Shell_NotifyIcon()
#ifdef _MSC_VER
#include <richedit.h> // For EM
#endif
//-------------------------------------------------------------------- CONSTANTS
//-------------------------------------------------------------------- VARIABLES
// Global
WNDPROC lpfnFrameProcOld = NULL;
WNDPROC lpfnEditProcOld = NULL;
WNDPROC lpfnHyperLinkProcOld = NULL;
WNDPROC lpfnLabelProcOld = NULL;
WNDPROC lpfnInvisibleProcOld = NULL;
// External
extern BOOL SetTaskBarIcon(HWND hwnd, BOOL bModify);
extern BOOL wbSetMenuItemText(PWBOBJ pwbo, LPCTSTR pszText);
extern DWORD GetCalendarTime(PWBOBJ pwbo);
extern BOOL SetCalendarTime(PWBOBJ pwbo, time_t UnixTime);
extern BOOL DisplayHTMLString(PWBOBJ pwbo, LPCTSTR string);
extern BOOL EmbedBrowserObject(PWBOBJ pwbo);
//---------------------------------------------------------- FUNCTION PROTOTYPES
// Global to the WinBinder API layer only
BOOL IsBitmap(HANDLE handle);
BOOL IsIcon(HANDLE handle);
BOOL RegisterImageButtonClass(void);
HWND CreateToolTip(PWBOBJ pwbo, LPCTSTR pszTooltip);
// Private
static BOOL SetTransparentBitmap(HWND hwnd, HBITMAP hbmBits, BOOL bStatic, COLORREF clTransp);
static LRESULT CALLBACK FrameProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK EditBoxProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK InvisibleProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK ImageButtonProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
// External
extern void SetStatusBarHandle(HWND hCtrl);
extern BOOL RegisterControlInTab(PWBOBJ pwboParent, PWBOBJ pwbo, UINT id, UINT nTab);
extern LRESULT CALLBACK HyperLinkProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
extern LRESULT CALLBACK LabelProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
//----------------------------------------------------------- EXPORTED FUNCTIONS
PWBOBJ wbCreateControl(PWBOBJ pwboParent, UINT uWinBinderClass, LPCTSTR pszSourceCaption, LPCTSTR pszSourceTooltip,
int xPos, int yPos, int nWidth, int nHeight, UINT id, DWORD dwWBStyle, long lParam, int nTab)
{
PWBOBJ pwbo;
LPTSTR pszClass;
int nVisible;
DWORD dwStyle, dwExStyle;
HWND hTab = NULL, hwndParent = NULL;
TCHAR *pszCaption;
TCHAR *pszTooltip;
if (!pwboParent || !pwboParent->hwnd || !IsWindow(pwboParent->hwnd))
{
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Cannot create control if parent window is NULL"));
return NULL;
}
pwbo = wbMalloc(sizeof(WBOBJ));
if (!pwbo)
return NULL;
wbConvertLineBreaks(&pszCaption, pszSourceCaption);
wbConvertLineBreaks(&pszTooltip, pszSourceTooltip);
pwbo->hwnd = NULL;
pwbo->id = id;
pwbo->uClass = uWinBinderClass;
pwbo->item = -1;
pwbo->subitem = -1;
pwbo->style = dwWBStyle;
pwbo->parent = pwboParent;
pwbo->pszCallBackFn = NULL;
pwbo->pszCallBackObj = NULL;
pwbo->lparam = lParam;
ZeroMemory(pwbo->lparams, sizeof(LONG) * 8);
ZeroMemory(&pwbo->rcTitle, sizeof(RECT) + 2 * sizeof(AREA));
pwbo->pbuffer = NULL;
// If parent is a tab control, change the parent to a page handle
if (pwboParent->uClass == TabControl)
{
PTABDATA pTabData;
pTabData = (PTABDATA)pwboParent->lparam;
// nTab is the page index
nTab = MIN(MIN((UINT)nTab, pTabData->nPages - 1), MAX_TABS);
hTab = pTabData->page[nTab].hwnd ? pTabData->page[nTab].hwnd : pwboParent->hwnd;
}
// Set visible / enabled flags
nVisible = BITTEST(dwWBStyle, WBC_INVISIBLE) ? 0 : WS_VISIBLE;
nVisible |= BITTEST(dwWBStyle, WBC_DISABLED) ? WS_DISABLED : 0;
if (BITTEST(dwWBStyle, WBC_BORDER))
dwExStyle = WS_EX_STATICEDGE;
else
dwExStyle = 0;
// Set Windows class and styles according to WinBinder class
switch (uWinBinderClass)
{
//-------------------------------- Regular child controls
case HyperLink:
pszClass = TEXT("STATIC");
dwStyle = WS_CHILD | SS_NOTIFY | SS_LEFT | nVisible;
dwExStyle = WS_EX_TRANSPARENT;
break;
case Label:
pszClass = TEXT("STATIC");
if (BITTEST(dwWBStyle, WBC_ELLIPSIS))
dwStyle = WS_CHILD | SS_WORDELLIPSIS | nVisible;
else
dwStyle = WS_CHILD | nVisible;
if (BITTEST(dwWBStyle, WBC_CENTER))
dwStyle |= SS_CENTER;
else if (BITTEST(dwWBStyle, WBC_RIGHT))
dwStyle |= SS_RIGHT;
else
{
dwStyle |= SS_LEFT;
if (!BITTEST(dwWBStyle, WBC_MULTILINE))
dwStyle |= SS_LEFTNOWORDWRAP;
}
break;
case Frame:
if ((nWidth > nHeight) && nHeight <= 8)
{ // Horizontal line
pszClass = TEXT("STATIC");
dwStyle = WS_CHILD | SS_ETCHEDHORZ | nVisible;
}
else if ((nWidth < nHeight) && nWidth <= 8)
{ // Vertical line
pszClass = TEXT("STATIC");
dwStyle = WS_CHILD | SS_ETCHEDVERT | nVisible;
}
else if (BITTEST(dwWBStyle, WBC_IMAGE))
{ // Image
pszClass = TEXT("STATIC");
dwStyle = WS_CHILD | SS_WORDELLIPSIS | SS_CENTERIMAGE | nVisible;
if (BITTEST(dwWBStyle, WBC_CENTER))
dwStyle |= SS_CENTER;
else if (BITTEST(dwWBStyle, WBC_RIGHT))
dwStyle |= SS_RIGHT;
else
dwStyle |= SS_LEFT;
}
else
{ // Group box
pszClass = TEXT("BUTTON");
dwStyle = WS_CHILD | WS_TABSTOP | BS_GROUPBOX | nVisible;
dwExStyle |= WS_EX_TRANSPARENT;
}
break;
case Calendar:
pszClass = MONTHCAL_CLASS;
dwStyle = (BITTEST(dwWBStyle, WBC_BORDER) ? WS_BORDER : 0) | WS_CHILD | WS_VISIBLE | MCS_DAYSTATE | nVisible;
break;
case PushButton:
pszClass = TEXT("BUTTON");
dwStyle = (BITTEST(dwWBStyle, WBC_BORDER) ? BS_DEFPUSHBUTTON : 0) | WS_CHILD | WS_TABSTOP | BS_PUSHBUTTON | BS_NOTIFY | nVisible;
break;
case InvisibleArea:
pszClass = TEXT("STATIC");
dwStyle = WS_CHILD | SS_NOTIFY | SS_BITMAP | nVisible;
dwExStyle = WS_EX_TRANSPARENT;
break;
case ImageButton:
pszClass = IMAGE_BUTTON_CLASS; // This is a custom control class
dwStyle = WS_CHILD | WS_TABSTOP | nVisible;
if (pwbo->style & WBC_TRANSPARENT)
dwExStyle = WS_EX_TRANSPARENT;
break;
case CheckBox:
pszClass = TEXT("BUTTON");
dwStyle = WS_CHILD | WS_TABSTOP | BS_AUTOCHECKBOX | BS_NOTIFY | nVisible;
break;
case RadioButton:
pszClass = TEXT("BUTTON");
dwStyle = WS_CHILD | WS_TABSTOP | BS_AUTORADIOBUTTON | BS_NOTIFY | nVisible;
if (BITTEST(dwWBStyle, WBC_GROUP))
dwStyle |= WS_GROUP;
break;
case EditBox:
pszClass = TEXT("EDIT");
dwStyle = WS_CHILD | WS_TABSTOP | nVisible;
if (BITTEST(dwWBStyle, WBC_READONLY))
dwStyle |= ES_READONLY;
if (BITTEST(dwWBStyle, WBC_MASKED))
dwStyle |= ES_PASSWORD;
if (BITTEST(dwWBStyle, WBC_NUMBER))
dwStyle |= ES_NUMBER;
if (BITTEST(dwWBStyle, WBC_MULTILINE))
{
if (BITTEST(dwWBStyle, WBC_READONLY))
dwStyle |= WS_VSCROLL | ES_MULTILINE;
else
dwStyle |= WS_VSCROLL | ES_MULTILINE | ES_WANTRETURN;
}
else
{
dwStyle |= ES_AUTOHSCROLL;
if (BITTEST(dwWBStyle, WBC_CENTER))
dwStyle |= ES_CENTER;
else if (BITTEST(dwWBStyle, WBC_RIGHT))
dwStyle |= ES_RIGHT;
else
dwStyle |= ES_LEFT;
}
dwExStyle |= WS_EX_CLIENTEDGE;
break;
case RTFEditBox:
pszClass = RICHEDITCONTROL;
dwStyle = WS_CHILD | WS_TABSTOP | nVisible;
if (BITTEST(dwWBStyle, WBC_READONLY))
dwStyle |= ES_READONLY | WS_VSCROLL | ES_MULTILINE;
else
dwStyle |= WS_VSCROLL | ES_MULTILINE | ES_WANTRETURN;
if (BITTEST(dwWBStyle, WBC_CENTER))
dwStyle |= ES_CENTER;
else if (BITTEST(dwWBStyle, WBC_RIGHT))
dwStyle |= ES_RIGHT;
else
dwStyle |= ES_LEFT;
dwExStyle |= WS_EX_CLIENTEDGE;
break;
case ListBox:
pszClass = TEXT("LISTBOX");
dwStyle = WS_CHILD | WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | nVisible;
if (BITTEST(dwWBStyle, WBC_SORT))
dwStyle |= LBS_SORT;
if (BITTEST(dwWBStyle, WBC_MULTISELECT))
dwStyle |= LBS_EXTENDEDSEL;
dwExStyle |= WS_EX_CLIENTEDGE;
break;
case ComboBox:
pszClass = TEXT("COMBOBOX");
dwStyle = WS_CHILD | WS_TABSTOP | WS_VSCROLL | nVisible;
if (BITTEST(dwWBStyle, WBC_READONLY))
dwStyle |= CBS_DROPDOWNLIST;
else
dwStyle |= CBS_DROPDOWN;
if (BITTEST(dwWBStyle, WBC_SORT))
dwStyle |= CBS_SORT;
break;
case ScrollBar:
pszClass = TEXT("SCROLLBAR");
if (nHeight >= nWidth)
dwStyle = WS_CHILD | WS_TABSTOP | SBS_VERT | nVisible;
else
dwStyle = WS_CHILD | WS_TABSTOP | nVisible;
break;
case ListView:
pszClass = WC_LISTVIEW;
dwStyle = WS_CHILD | WS_TABSTOP | LVS_REPORT | LVS_SHOWSELALWAYS | LVS_NOLABELWRAP | nVisible;
if (!BITTEST(dwWBStyle, WBC_SORT))
dwStyle |= LVS_NOSORTHEADER;
if (BITTEST(dwWBStyle, WBC_SINGLE))
dwStyle |= LVS_SINGLESEL;
if (BITTEST(dwWBStyle, WBC_NOHEADER))
dwStyle |= LVS_NOCOLUMNHEADER;
dwExStyle |= WS_EX_CLIENTEDGE;
break;
case Spinner:
pszClass = UPDOWN_CLASS;
if (BITTEST(dwWBStyle, WBC_GROUP))
dwStyle = WS_CHILD | WS_TABSTOP | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_AUTOBUDDY | UDS_SETBUDDYINT | nVisible;
else
dwStyle = WS_CHILD | WS_TABSTOP | UDS_ARROWKEYS | UDS_NOTHOUSANDS | nVisible;
break;
case Gauge:
pszClass = PROGRESS_CLASS;
dwStyle = WS_CHILD | nVisible;
break;
case Slider:
pszClass = TRACKBAR_CLASS;
if (BITTEST(dwWBStyle, WBC_LINES))
dwStyle = WS_CHILD | WS_TABSTOP | TBS_AUTOTICKS | nVisible;
else
dwStyle = WS_CHILD | WS_TABSTOP | TBS_NOTICKS | nVisible;
break;
case TreeView:
{
PTREEDATA ptrdt;
int i;
pszClass = WC_TREEVIEW;
dwStyle = WS_CHILD | WS_TABSTOP | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_SHOWSELALWAYS | nVisible;
dwExStyle |= WS_EX_CLIENTEDGE;
// Attach a structure to the treeview control and initialize it
ptrdt = wbMalloc(sizeof(TREEDATA));
// memset(ptrdt, 0, sizeof(TREEDATA));
ptrdt->hLast = TVI_ROOT;
for (i = 0; i < MAX_TREEVIEW_LEVELS; i++)
{
ptrdt->hParent[i] = TVI_ROOT;
ptrdt->bCustomImages[i] = FALSE;
}
ptrdt->nLastLevel = 0;
pwbo->lparam = (LPARAM)ptrdt;
}
break;
case StatusBar:
pszClass = STATUSCLASSNAME;
if (BITTEST(GetWindowLong(pwboParent->hwnd, GWL_STYLE), WS_THICKFRAME))
dwStyle = WS_CHILD | CCS_BOTTOM | CCS_NOMOVEY | SBARS_SIZEGRIP | nVisible;
else
dwStyle = WS_CHILD | CCS_BOTTOM | CCS_NOMOVEY | nVisible;
break;
case TabControl:
pszClass = WC_TABCONTROL;
dwStyle = WS_CHILD | WS_TABSTOP | WS_CLIPCHILDREN | nVisible;
{
PTABDATA pTabData;
// Alloc memory for tab data
pTabData = wbMalloc(sizeof(TABDATA));
memset(pTabData, 0, sizeof(TABDATA));
pwbo->lparam = (LPARAM)pTabData;
pwbo->uClass = TabControl;
}
break;
case HTMLControl:
pszClass = BROWSER_WINDOW_CLASS;
dwStyle = WS_CHILD | nVisible;
break;
default:
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Unknown control class %d"), uWinBinderClass);
return NULL;
} // end switch
// Create the control
hwndParent = (pwboParent->uClass == TabControl) ? hTab : (pwboParent ? pwboParent->hwnd : NULL);
pwbo->hwnd = CreateWindowEx(
dwExStyle,
pszClass,
pszCaption && *pszCaption ? pszCaption : TEXT(""),
dwStyle,
xPos, yPos, nWidth, nHeight,
hwndParent,
(HMENU)id,
hAppInstance,
NULL);
if (!pwbo->hwnd)
{
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Error creating control of class %d ('%s')"),
uWinBinderClass, pszClass);
return NULL;
}
// Further processing after control creation
switch (pwbo->uClass)
{
case HTMLControl:
EmbedBrowserObject(pwbo);
break;
case RadioButton:
case CheckBox:
case PushButton:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
if (lParam) // Check button
SendMessage(pwbo->hwnd, BM_SETCHECK, TRUE, 0);
CreateToolTip(pwbo, pszTooltip);
break;
case EditBox: // Subclasses edit box to process keyboard messages
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
lpfnEditProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)EditBoxProc);
CreateToolTip(pwbo, pszTooltip);
break;
case TabControl:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
// // Subclasses tab control to process WM_COMMAND
// lpfnTabProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)TabProc);
CreateToolTip(pwbo, pszTooltip);
wbSetTabControlText(pwbo, pszCaption);
// Assign window handler, if any
// if(pwbo->parent && pwbo->parent->pszCallBackFn && *pwbo->parent->pszCallBackFn)
// pwbo->pszCallBackFn = pwbo->parent->pszCallBackFn;
break;
case Frame: // Subclasses Frame control to process WM_COMMAND
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
if (!wcsicmp(pszClass, TEXT("BUTTON"))) // Only for group boxes!
lpfnFrameProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)FrameProc);
break;
case InvisibleArea: // Subclasses InvisibleArea to process WM_MOUSEMOVE
CreateToolTip(pwbo, pszTooltip);
lpfnInvisibleProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)InvisibleProc);
wbSetCursor(pwbo, NULL, 0); // Assumes class cursor
break;
case ImageButton:
CreateToolTip(pwbo, pszTooltip);
wbSetCursor(pwbo, NULL, 0); // Assumes class cursor
if (!(pwbo->style & WBC_TRANSPARENT))
{
HIMAGELIST hi;
static int nImages = 4;
hi = ImageList_Create(nWidth, nHeight, ILC_COLORDDB, nImages, 0);
M_hiImageList = (LPARAM)hi; // Store ImageList in control
}
break;
case Spinner:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
SendMessage(pwbo->hwnd, UDM_SETRANGE, 0, MAKELONG(100, 0));
SendMessage(pwbo->hwnd, UDM_SETPOS, 0, MAKELONG((short)0, 0));
CreateToolTip(pwbo, pszTooltip);
break;
case ScrollBar:
SendMessage(pwbo->hwnd, SBM_SETRANGE, 0, 100);
CreateToolTip(pwbo, pszTooltip);
break;
case StatusBar:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
SetStatusBarHandle(pwbo->hwnd);
CreateToolTip(pwbo, pszTooltip);
break;
case ListView:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
SendMessage(pwbo->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP | LVS_EX_LABELTIP | LVS_EX_SUBITEMIMAGES);
break;
case RTFEditBox:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
SendMessage(pwbo->hwnd, EM_FMTLINES, TRUE, 0);
SendMessage(pwbo->hwnd, EM_SETEVENTMASK, 0, ENM_CHANGE); // Enables EN_CHANGE messages. Should be EN_UPDATE instead?
SetWindowText(pwbo->hwnd, pszCaption);
CreateToolTip(pwbo, pszTooltip);
break;
case HyperLink:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
// Subclasses static control
lpfnHyperLinkProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)HyperLinkProc);
wbSetCursor(pwbo, NULL, 0); // Assumes class cursor
CreateToolTip(pwbo, pszTooltip);
break;
case Label:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
// Subclasses static control
lpfnLabelProcOld = (WNDPROC)SetWindowLong(pwbo->hwnd, GWL_WNDPROC, (LONG)LabelProc);
wbSetCursor(pwbo, NULL, 0); // Assumes class cursor
CreateToolTip(pwbo, pszTooltip);
break;
case Calendar:
case ListBox:
case ComboBox:
case Gauge:
case Slider:
case TreeView:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
CreateToolTip(pwbo, pszTooltip);
break;
default:
SendMessage(pwbo->hwnd, WM_SETFONT, (WPARAM)hIconFont, 0);
break;
}
// Add any additional styles that may be present
wbSetStyle(pwbo, dwWBStyle, TRUE);
// Is the parent window a tab control?
if (pwboParent->uClass == TabControl)
RegisterControlInTab(pwboParent, pwbo, id, nTab);
SetWindowLong(pwbo->hwnd, GWL_USERDATA, (LONG)pwbo);
return pwbo;
}
/* Destroy a control created by wbCreateControl(). */
BOOL wbDestroyControl(PWBOBJ pwbo)
{
if (!pwbo || !pwbo->hwnd || !IsWindow(pwbo->hwnd))
return FALSE;
switch (pwbo->uClass)
{
case TreeView:
case TabControl:
wbFree((void *)pwbo->lparam);
break;
}
return DestroyWindow(pwbo->hwnd);
}
PWBOBJ wbGetControl(PWBOBJ pwboParent, int id)
{
PWBOBJ pwbo = NULL;
if (!wbIsWBObj(pwboParent, TRUE))
{ // Is it a valid control?
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("First parameter is not a valid WinBinder control"));
return NULL;
}
if (pwboParent->uClass == Menu)
{
if (IsMenu((HMENU)pwboParent->hwnd))
{ // Is it a menu?
MENUITEMINFO mi;
mi.cbSize = sizeof(MENUITEMINFO);
mi.fMask = MIIM_ID;
if (GetMenuItemInfo((HMENU)pwboParent->hwnd, id, FALSE, &mi))
{
pwbo = wbMalloc(sizeof(WBOBJ));
memcpy(pwbo, pwboParent, sizeof(WBOBJ));
pwbo->id = id;
}
else
{
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Menu item #%d not found in menu #%d"), id, (int)pwboParent->hwnd);
return NULL;
}
}
else
{
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Menu object does not have a valid menu handle"));
return NULL;
}
}
else if (!IsWindow(pwboParent->hwnd))
{ // Is it a window?
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Object does not have a valid window handle"));
return NULL;
}
else
{ // Yes, it's a window
switch (pwboParent->uClass)
{
case ToolBar: // It's a toolbar
pwbo = wbMalloc(sizeof(WBOBJ));
pwbo->hwnd = pwboParent->hwnd;
pwbo->id = id;
pwbo->uClass = pwboParent->uClass;
pwbo->item = -1;
pwbo->subitem = -1;
pwbo->style = 0;
pwbo->parent = pwboParent;
pwbo->pszCallBackFn = NULL;
pwbo->pszCallBackObj = NULL;
pwbo->lparam = 0;
pwbo->pbuffer = NULL;
break;
default: // Regular window classes
{
HWND hCtrl;
hCtrl = GetDlgItem(pwboParent->hwnd, id);
if (hCtrl)
{
// It's a regular control
if (IsWindow(hCtrl))
{
pwbo = (PWBOBJ)GetWindowLong(hCtrl, GWL_USERDATA);
}
else
{
pwbo = wbMalloc(sizeof(WBOBJ));
pwbo->hwnd = hCtrl;
pwbo->id = id;
pwbo->uClass = pwboParent->uClass;
pwbo->item = -1;
pwbo->subitem = -1;
pwbo->style = 0;
pwbo->parent = pwboParent;
pwbo->pszCallBackFn = NULL;
pwbo->pszCallBackObj = NULL;
pwbo->lparam = 0;
pwbo->pbuffer = NULL;
}
}
else
{
// Is its parent a tab control?
if (pwboParent->uClass == TabControl)
{
// Yes, let's try to find it
PTABDATA pTabData;
UINT i;
pTabData = (PTABDATA)pwboParent->lparam;
for (i = 0; i < pTabData->nCtrls; i++)
{
if (pTabData->ctrl[i].id == (UINT)id)
{
hCtrl = pTabData->ctrl[i].hwnd;
if (IsWindow(hCtrl))
{
pwbo = (PWBOBJ)GetWindowLong(hCtrl, GWL_USERDATA);
}
else
{
pwbo = NULL;
}
break;
}
}
}
else
{
// No, control does not exist
TCHAR szText[256];
wbGetText(pwboParent, szText, 255, -1);
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Control #%d not found in window '%s'"), id, szText);
return NULL;
}
}
}
} // switch
} // else
return pwbo;
}
/* Create status bar parts */
BOOL wbSetStatusBarParts(PWBOBJ pwbo, int nParts, int *aWidths)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (pwbo->uClass != StatusBar)
return FALSE;
nParts = min(max(0, nParts), 255);
return SendMessage(pwbo->hwnd, SB_SETPARTS, nParts, (LPARAM)aWidths);
}
BOOL wbSetText(PWBOBJ pwbo, LPCTSTR pszSourceText, int nItem, BOOL bTooltip)
{
TCHAR *pszText;
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
wbConvertLineBreaks(&pszText, pszSourceText);
if (bTooltip)
{
HWND hwndTT;
TOOLINFO ti;
hwndTT = (HWND)M_ToolTipWnd;
if (!hwndTT)
return FALSE;
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = 0;
ti.hwnd = pwbo->hwnd;
ti.uId = 0;
ti.hinst = NULL;
ti.lpszText = (LPTSTR)pszText;
SendMessage(hwndTT, TTM_UPDATETIPTEXT, 0, (LPARAM)&ti);
return TRUE;
}
else
{
switch (pwbo->uClass)
{
case Spinner:
// Change text of "buddy" control. The buddy is the edit box attached to the Up-down control
{
HWND hBuddy = (HWND)SendMessage(pwbo->hwnd, UDM_GETBUDDY, 0, 0);
if (hBuddy)
return SetWindowText(hBuddy, pszText);
else
return FALSE;
}
break;
case TabControl:
return wbSetTabControlText(pwbo, pszText);
case Menu:
pwbo->id = nItem;
return wbSetMenuItemText(pwbo, pszText);
case HTMLControl:
// if(nItem)
// return DisplayHTMLPage(pwbo, pszText);
// else
return DisplayHTMLString(pwbo, pszText);
case StatusBar:
if (SendMessage(pwbo->hwnd, SB_GETPARTS, 0, 0) > 1)
return SendMessage(pwbo->hwnd, SB_SETTEXT, nItem | 0, (LPARAM)(pszText ? pszText : TEXT("")));
else
return SetWindowText(pwbo->hwnd, pszText);
default:
return SetWindowText(pwbo->hwnd, pszText);
}
}
}
/*
Limitation: Treeview items <= 1024 characters
*/
UINT wbGetTextLength(PWBOBJ pwbo, int nIndex)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case Spinner:
{
// Measure length of text of "buddy" control. The buddy is the edit box attached to the Up-down control
HWND hBuddy;
hBuddy = (HWND)SendMessage(pwbo->hwnd, UDM_GETBUDDY, 0, 0);
return GetWindowTextLength(hBuddy);
}
case ListBox:
{
if (nIndex < 0)
{
if (pwbo->item < 0)
{
nIndex = SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
if (nIndex == LB_ERR)
return 0;
}
else
{
nIndex = pwbo->item;
}
}
return SendMessage(pwbo->hwnd, LB_GETTEXTLEN, nIndex, 0);
}
case ComboBox:
{
if (nIndex < 0)
{
if (!(pwbo->style & WBC_READONLY))
return SendMessage(pwbo->hwnd, WM_GETTEXTLENGTH, 0, 0);
else
{
if (pwbo->item < 0)
{
nIndex = SendMessage(pwbo->hwnd, CB_GETCURSEL, 0, 0);
if (nIndex == CB_ERR)
return 0;
}
else
{
nIndex = pwbo->item;
}
}
}
return SendMessage(pwbo->hwnd, CB_GETLBTEXTLEN, nIndex, 0);
}
case TreeView:
{
TV_ITEM tvi;
TCHAR szText[MAX_ITEM_STRING];
tvi.hItem = TreeView_GetSelection(pwbo->hwnd);
if (!tvi.hItem)
return 0;
tvi.pszText = szText;
tvi.cchTextMax = MAX_ITEM_STRING;
tvi.mask = TVIF_TEXT;
TreeView_GetItem(pwbo->hwnd, &tvi);
if (tvi.pszText && *tvi.pszText)
return wcslen(tvi.pszText);
else
return 0;
}
default:
return GetWindowTextLength(pwbo->hwnd);
}
}
DWORD CALLBACK EditStreamOutCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG *pcb)
{
char **rtf = (char **)dwCookie;
*rtf = wbMalloc(cb + 1);
//strcpy_s(*rtf, cb, pbBuff);
memset(*rtf, 0, cb + 1);
memcpy(*rtf, pbBuff, cb);
*pcb = cb;
return 0;
}
BOOL wbGetRtfText(PWBOBJ pwbo, char **unc)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case RTFEditBox:
{
EDITSTREAM es = {0};
es.dwCookie = (DWORD_PTR)unc;
es.pfnCallback = &EditStreamOutCallback;
SendMessage(pwbo->hwnd, EM_STREAMOUT, (WPARAM)(SF_RTF), (LPARAM)&es);
//use SF_TEXT|SF_UNICODE then you need
return TRUE;
}
}
return FALSE;
}
BOOL wbGetText(PWBOBJ pwbo, LPTSTR pszText, UINT nMaxChars, int nIndex)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (!nMaxChars)
return FALSE;
*pszText = '\0';
switch (pwbo->uClass)
{
case Spinner:
{
// Reads text of "buddy" control. The buddy is the edit box attached to the Up-down control
HWND hBuddy;
hBuddy = (HWND)SendMessage(pwbo->hwnd, UDM_GETBUDDY, 0, 0);
GetWindowText(hBuddy, pszText, nMaxChars);
return TRUE;
}
case ListBox:
{
BOOL bRet;
if (nIndex < 0)
{
if (pwbo->item < 0)
{
nIndex = SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
if (nIndex == LB_ERR)
return FALSE;
}
else
{
nIndex = pwbo->item;
}
}
bRet = SendMessage(pwbo->hwnd, LB_GETTEXT, nIndex, (LPARAM)(LPTSTR)pszText);
return (bRet != LB_ERR);
}
case ComboBox:
{
BOOL bRet;
if (nIndex < 0)
{
if (!(pwbo->style & WBC_READONLY))
{
SendMessage(pwbo->hwnd, WM_GETTEXT, nMaxChars, (LPARAM)pszText);
return TRUE;
}
else
{
if (pwbo->item < 0)
{
nIndex = SendMessage(pwbo->hwnd, CB_GETCURSEL, 0, 0);
if (nIndex == CB_ERR)
{
return FALSE;
}
}
else
{
nIndex = pwbo->item;
}
}
}
bRet = SendMessage(pwbo->hwnd, CB_GETLBTEXT, nIndex, (LPARAM)(LPTSTR)pszText);
return (bRet != CB_ERR);
}
case TreeView:
{
TV_ITEM tvi;
tvi.hItem = TreeView_GetSelection(pwbo->hwnd);
if (!tvi.hItem)
return FALSE;
tvi.pszText = pszText;
tvi.cchTextMax = nMaxChars;
tvi.mask = TVIF_TEXT;
TreeView_GetItem(pwbo->hwnd, &tvi);
return (tvi.pszText && *tvi.pszText);
}
default:
GetWindowText(pwbo->hwnd, pszText, nMaxChars);
return TRUE;
}
}
BOOL wbSetEnabled(PWBOBJ pwbo, BOOL bState)
{
BOOL bRet;
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
// Change status flag
if (pwbo->uClass == Menu && IsMenu((HMENU)pwbo->hwnd))
{ // Is it a menu item?
MENUITEMINFO mi;
mi.cbSize = sizeof(MENUITEMINFO);
mi.fMask = MIIM_STATE;
mi.fState = bState ? MFS_ENABLED : (MFS_DISABLED | MFS_GRAYED);
bRet = SetMenuItemInfo((HMENU)pwbo->hwnd, pwbo->id, FALSE, &mi);
if (!bRet)
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Could not set state of menu item #%d"), pwbo->id);
}
else if (IsWindow(pwbo->hwnd))
{ // Is it a window?
switch (pwbo->uClass)
{
case ToolBar:
bRet = SendMessage((HWND)pwbo->hwnd, TB_ENABLEBUTTON, pwbo->id, MAKELONG(bState, 0));
break;
default:
EnableWindow(pwbo->hwnd, bState ? 1 : 0);
// Should NOT use the return value from EnableWindow()
bRet = TRUE;
break;
}
// Force draw custom-drawn controls when they change state
if (bRet && (pwbo->uClass == ImageButton))
InvalidateRect(pwbo->hwnd, NULL, FALSE);
}
else
bRet = FALSE;
// Change style according to bState
if (bRet && bState)
pwbo->style &= ~WBC_DISABLED;
else
pwbo->style |= WBC_DISABLED;
return bRet;
}
BOOL wbGetEnabled(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (pwbo->uClass == Menu && IsMenu((HMENU)pwbo->hwnd))
{ // Is it a menu item?
MENUITEMINFO mi;
mi.cbSize = sizeof(MENUITEMINFO);
mi.fMask = MIIM_STATE;
if (!GetMenuItemInfo((HMENU)pwbo->hwnd, pwbo->id, FALSE, &mi))
{
wbError(TEXT(__FUNCTION__), MB_ICONWARNING, TEXT("Could not get state of menu item #%d."), pwbo->id);
return FALSE;
}
return (mi.fState & (MFS_DISABLED | MFS_GRAYED) ? FALSE : TRUE);
}
else if (IsWindow(pwbo->hwnd))
{ // Is it a window?
switch (pwbo->uClass)
{
case ToolBar: // Toolbar
return SendMessage(pwbo->hwnd, TB_ISBUTTONENABLED, pwbo->id, 0);
default:
return IsWindowEnabled(pwbo->hwnd); // The window
}
}
else
return FALSE;
}
DWORD wbGetSelected(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case ComboBox:
// lparam < 0 means the child edit control was modified
if (pwbo->lparam < 0)
return -1;
else
return SendMessage(pwbo->hwnd, CB_GETCURSEL, 0, 0);
case ListBox:
return SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
case TabControl:
return SendMessage(pwbo->hwnd, TCM_GETCURSEL, 0, 0);
case CheckBox:
case RadioButton:
// 0 means unchecked, 1 means checked.
return (SendMessage(pwbo->hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED);
case EditBox:
case HyperLink:
case ImageButton:
case Label:
case Menu:
case PushButton:
case RTFEditBox:
case Slider:
case Spinner:
return 0;
default:
return 0;
}
}
DWORD wbGetItemCount(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case ListView:
return SendMessage(pwbo->hwnd, LVM_GETITEMCOUNT, 0, 0);
case ListBox:
return SendMessage(pwbo->hwnd, LB_GETCOUNT, 0, 0);
case ComboBox:
return SendMessage(pwbo->hwnd, CB_GETCOUNT, 0, 0);
default:
return 0;
}
}
BOOL wbDeleteItems(PWBOBJ pwbo, BOOL bClearAll)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case ListBox:
if (!bClearAll)
SendMessage(pwbo->hwnd, LB_DELETESTRING, pwbo->item, 0);
else
SendMessage(pwbo->hwnd, LB_RESETCONTENT, 0, 0);
break;
case ComboBox:
if (!bClearAll)
SendMessage(pwbo->hwnd, CB_DELETESTRING, pwbo->item, 0);
else
SendMessage(pwbo->hwnd, CB_RESETCONTENT, 0, 0);
break;
case ListView:
if (!bClearAll)
return ListView_DeleteItem(pwbo->hwnd, pwbo->item);
else
return SendMessage(pwbo->hwnd, LVM_DELETEALLITEMS, 0, 0);
break;
case TreeView:
if (!bClearAll)
{
if (pwbo->item)
return SendMessage(pwbo->hwnd, TVM_DELETEITEM, 0, (LPARAM)(HTREEITEM)pwbo->item);
}
else
{
PTREEDATA ptrdt = (PTREEDATA)pwbo->lparam;
int i;
// Clear the treeview data
ptrdt = wbMalloc(sizeof(TREEDATA));
ptrdt->hLast = TVI_ROOT;
for (i = 0; i < MAX_TREEVIEW_LEVELS; i++)
{
ptrdt->hParent[i] = TVI_ROOT;
ptrdt->bCustomImages[i] = FALSE;
}
ptrdt->nLastLevel = 0;
pwbo->lparam = (LPARAM)ptrdt;
}
return TreeView_DeleteAllItems(pwbo->hwnd);
}
return TRUE;
}
BOOL wbGetVisible(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
return IsWindowVisible(pwbo->hwnd);
}
BOOL wbSetVisible(PWBOBJ pwbo, BOOL bState)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
SetWindowPos(pwbo->hwnd, 0, 0, 0, 0, 0, (bState ? SWP_SHOWWINDOW : SWP_HIDEWINDOW) | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER);
return TRUE;
}
PWBOBJ wbGetFocus(void)
{
return wbGetWBObj(GetFocus());
}
BOOL wbSetFocus(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case EditBox:
SendMessage(pwbo->hwnd, EM_SETSEL, 0, -1); // Select all
break;
}
return (SetFocus(pwbo->hwnd) != NULL);
}
// Sets the styles of some controls
BOOL wbSetStyle(PWBOBJ pwbo, DWORD dwWBStyle, BOOL bSet)
{
switch (pwbo->uClass)
{
case AppWindow:
case ResizableWindow:
case PopupWindow:
case NakedWindow:
if (bSet)
{
if (BITTEST(dwWBStyle, WBC_TOP))
SetWindowPos(pwbo->hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
else
{
if (BITTEST(dwWBStyle, WBC_TOP))
SetWindowPos(pwbo->hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
break;
case ListView:
if (bSet)
{
if (BITTEST(dwWBStyle, WBC_LINES))
SendMessage(pwbo->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_GRIDLINES, LVS_EX_GRIDLINES);
if (BITTEST(dwWBStyle, WBC_CHECKBOXES))
SendMessage(pwbo->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_CHECKBOXES, LVS_EX_CHECKBOXES);
}
else
{
if (BITTEST(dwWBStyle, WBC_LINES))
SendMessage(pwbo->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_GRIDLINES, 0);
if (BITTEST(dwWBStyle, WBC_CHECKBOXES))
SendMessage(pwbo->hwnd, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_CHECKBOXES, 0);
}
break;
case TreeView:
if (bSet)
{
if (BITTEST(dwWBStyle, WBC_LINES))
SetWindowLong(pwbo->hwnd, GWL_STYLE, GetWindowLong(pwbo->hwnd, GWL_STYLE) | (TVS_HASLINES));
}
else
{
if (BITTEST(dwWBStyle, WBC_LINES))
{
SetWindowLong(pwbo->hwnd, GWL_STYLE, GetWindowLong(pwbo->hwnd, GWL_STYLE) & ~(TVS_HASLINES));
}
}
break;
case Slider:
if (bSet)
{
if (BITTEST(dwWBStyle, WBC_LINES))
SendMessage(pwbo->hwnd, TBM_SETTICFREQ, 10, 1);
}
else
{
if (BITTEST(dwWBStyle, WBC_LINES))
{
SendMessage(pwbo->hwnd, TBM_CLEARTICS, 1, 0);
}
}
break;
default:
return FALSE;
}
return TRUE;
}
BOOL wbSetValue(PWBOBJ pwbo, DWORD dwValue)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
case ListBox:
if (pwbo->item < 0)
pwbo->item = SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
return SendMessage(pwbo->hwnd, LB_SETITEMDATA, pwbo->item, dwValue);
case ComboBox:
if (pwbo->item < 0)
pwbo->item = SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
return SendMessage(pwbo->hwnd, CB_SETITEMDATA, pwbo->item, dwValue);
case Slider:
return SendMessage(pwbo->hwnd, TBM_SETPOS, TRUE, dwValue);
case Gauge:
return SendMessage(pwbo->hwnd, PBM_SETPOS, (WPARAM)dwValue, 0);
case Spinner:
return SendMessage(pwbo->hwnd, UDM_SETPOS, 0, MAKELONG((short)dwValue, 0));
case ScrollBar:
return SendMessage(pwbo->hwnd, SBM_SETPOS, (WPARAM)dwValue, TRUE);
case Calendar:
return SetCalendarTime(pwbo, dwValue);
// Set value as text
case EditBox:
case RTFEditBox:
case Label:
{
TCHAR szText[32];
_itow(dwValue, szText, 10);
return SetWindowText(pwbo->hwnd, szText);
}
// Check / uncheck button
case PushButton:
case CheckBox:
case RadioButton:
return SendMessage(pwbo->hwnd, BM_SETCHECK, dwValue, 0);
// Check/uncheck menu item
case Menu:
return wbSetMenuItemChecked(pwbo, dwValue);
}
return TRUE;
}
BOOL wbSetRange(PWBOBJ pwbo, LONG lMin, LONG lMax)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
switch (pwbo->uClass)
{
// Set range
case Slider:
SendMessage(pwbo->hwnd, TBM_SETRANGEMIN, FALSE, lMin);
SendMessage(pwbo->hwnd, TBM_SETRANGEMAX, TRUE, lMax);
break;
case Gauge:
SendMessage(pwbo->hwnd, PBM_SETRANGE32, lMin, lMax);
break;
case Spinner: // Inverted so that the control increases upwards
SendMessage(pwbo->hwnd, UDM_SETRANGE32, lMin, lMax);
break;
case ScrollBar:
SendMessage(pwbo->hwnd, SBM_SETRANGE, lMin, lMax);
break;
}
return TRUE;
}
DWORD wbGetValue(PWBOBJ pwbo)
{
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return 0;
switch (pwbo->uClass)
{
case Calendar:
return GetCalendarTime(pwbo);
case ListBox:
if (pwbo->item < 0)
pwbo->item = SendMessage(pwbo->hwnd, LB_GETCURSEL, 0, 0);
return SendMessage(pwbo->hwnd, LB_GETITEMDATA, pwbo->item, 0);
case ComboBox:
if (pwbo->item < 0)
pwbo->item = SendMessage(pwbo->hwnd, CB_GETCURSEL, 0, 0);
// lparam < 0 means the child edit control was modified
if (pwbo->lparam < 0)
return -1;
else
return SendMessage(pwbo->hwnd, CB_GETITEMDATA, pwbo->item, 0);
case EditBox:
case Label:
case PushButton:
case RTFEditBox:
{
TCHAR szText[65];
wbGetText(pwbo, szText, 64, -1);
return _wtoi(szText);
}
case Slider:
return SendMessage(pwbo->hwnd, TBM_GETPOS, 0, 0);
case Spinner:
return LOWORD(SendMessage(pwbo->hwnd, UDM_GETPOS, 0, 0));
case ScrollBar:
return SendMessage(pwbo->hwnd, SBM_GETPOS, 0, 0);
case CheckBox:
case RadioButton:
// 0 means unchecked, 1 means checked.
return (SendMessage(pwbo->hwnd, BM_GETCHECK, 0, 0) == BST_CHECKED);
case TreeView:
{
TV_ITEM tvi;
tvi.hItem = TreeView_GetSelection(pwbo->hwnd);
return wbGetTreeViewItemValue(pwbo, tvi.hItem);
}
case ListView:
return wbGetListViewItemChecked(pwbo, pwbo->item);
case Menu:
return wbGetMenuItemChecked(pwbo);
default:
return 0;
}
}
BOOL wbSetImage(PWBOBJ pwbo, HANDLE hImage, COLORREF clTransp, LPARAM lParam)
{
BOOL bRet = TRUE;
LONG lStyle;
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (!hImage)
return FALSE;
switch (pwbo->uClass)
{
case Menu:
wbSetMenuItemImage(pwbo, hImage);
break;
case PushButton:
lStyle = GetWindowLong(pwbo->hwnd, GWL_STYLE) & ~(BS_ICON | BS_BITMAP);
bRet = TRUE;
if (IsIcon(hImage))
{
SetWindowLong(pwbo->hwnd, GWL_STYLE, lStyle | BS_ICON);
SendMessage(pwbo->hwnd, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hImage);
break;
}
else if (IsBitmap(hImage))
{
SetWindowLong(pwbo->hwnd, GWL_STYLE, lStyle | BS_BITMAP);
bRet = SetTransparentBitmap(pwbo->hwnd, (HBITMAP)hImage, FALSE, clTransp);
break;
}
else
bRet = FALSE;
break;
case ImageButton:
if (IsBitmap(hImage))
{
HIMAGELIST hi;
hi = (HIMAGELIST)M_hiImageList; // Retrieve ImageList from control
if (clTransp == NOCOLOR)
ImageList_Add(hi, hImage, NULL);
else
ImageList_AddMasked(hi, hImage, clTransp);
break;
}
else
bRet = FALSE;
break;
case Frame:
lStyle = GetWindowLong(pwbo->hwnd, GWL_STYLE) & ~(SS_ICON | SS_BITMAP);
bRet = TRUE;
if (IsIcon(hImage))
{
SetWindowLong(pwbo->hwnd, GWL_STYLE, lStyle | SS_ICON);
SendMessage(pwbo->hwnd, STM_SETIMAGE, IMAGE_ICON, (LPARAM)hImage);
InvalidateRect(pwbo->hwnd, NULL, FALSE);
break;
}
else if (IsBitmap(hImage))
{
SetWindowLong(pwbo->hwnd, GWL_STYLE, lStyle | SS_BITMAP);
SetTransparentBitmap(pwbo->hwnd, (HBITMAP)hImage, TRUE, clTransp);
InvalidateRect(pwbo->hwnd, NULL, FALSE);
break;
}
else
bRet = FALSE;
break;
case ListView:
lParam = MAX(1, lParam); // Image count
bRet = wbCreateListViewImageList(pwbo, hImage, lParam, clTransp);
break;
case TabControl:
lParam = MAX(1, lParam); // Image count
bRet = wbCreateTabControlImageList(pwbo, hImage, lParam, clTransp);
break;
case TreeView:
lParam = MAX(1, lParam); // Image count
bRet = wbCreateTreeViewImageList(pwbo, hImage, lParam, clTransp);
break;
default:
// Set the window icon
SendMessage(pwbo->hwnd, WM_SETICON, ICON_BIG, (WPARAM)hImage);
bRet = TRUE;
// Change the icon in the taskbar if it is the case
if ((pwbo->style & WBC_TASKBAR) && IsIconic(pwbo->hwnd))
bRet = SetTaskBarIcon(pwbo->hwnd, TRUE);
} // end switch
return bRet;
}
BOOL wbCreateItem(PWBOBJ pwbo, LPCTSTR pszItemText)
{
LRESULT lRet;
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (!pszItemText || !*pszItemText)
return FALSE;
switch (pwbo->uClass)
{
case ListBox:
lRet = SendMessage(pwbo->hwnd, LB_ADDSTRING, 0, (LPARAM)pszItemText);
return ((lRet != LB_ERR) && (lRet != LB_ERRSPACE));
case ComboBox:
lRet = SendMessage(pwbo->hwnd, CB_ADDSTRING, 0, (LPARAM)pszItemText);
if (lRet == CB_ERR || lRet == CB_ERRSPACE)
return FALSE;
lRet = SendMessage(pwbo->hwnd, CB_SETCURSEL, 0, 0);
return (lRet != CB_ERR);
case TabControl:
return wbCreateTabItem(pwbo, pszItemText);
default:
return FALSE;
}
}
/* Refresh a window or control. */
BOOL wbRefreshControl(PWBOBJ pwbo, int xpos, int ypos, int nWidth, int nHeight, BOOL bNow)
{
BOOL bRet;
RECT rc;
if (!wbIsWBObj(pwbo, TRUE)) // Is it a valid control?
return FALSE;
if (!IsWindow(pwbo->hwnd))
return FALSE;
if (!((pwbo->style & WBC_NOTIFY) && (pwbo->lparam & WBC_REDRAW) && pwbo->pszCallBackFn && *pwbo->pszCallBackFn))
{
// Not custom drawn
if (nWidth <= 0 || nHeight <= 0)
{
bRet = InvalidateRect(pwbo->hwnd, NULL, TRUE); // Whole control
}
else
{
rc.left = xpos;
rc.top = ypos;
rc.right = xpos + nWidth;
rc.bottom = ypos + nHeight;
bRet = InvalidateRect(pwbo->hwnd, &rc, TRUE);
}
// Force an immediate update
if (bNow)
{
bRet = UpdateWindow(pwbo->hwnd);
}
}
else
{
// Custom drawn
if (nWidth <= 0 || nHeight <= 0)
{
// We use the callback function to let the user do the drawing
// *** Should probably use pwbo->parent for child controls, but the
// *** use of parameter pwboParent in wbCallUserFunction() is not clear
wbCallUserFunction(pwbo->pszCallBackFn, pwbo->pszCallBackObj, pwbo, pwbo,
IDDEFAULT, WBC_REDRAW, (LPARAM)pwbo->pbuffer, 0);
bRet = InvalidateRect(pwbo->hwnd, NULL, TRUE);
// Force an immediate update
if (bNow)
{
bRet = UpdateWindow(pwbo->hwnd);
}
}
else
{
rc.left = xpos;
rc.top = ypos;
rc.right = xpos + nWidth;
rc.bottom = ypos + nHeight;
// We use the callback function to let the user do the drawing
// *** Should probably use pwbo->parent for child controls, but the
// *** use of parameter pwboParent in wbCallUserFunction() is not clear
wbCallUserFunction(pwbo->pszCallBackFn, pwbo->pszCallBackObj, pwbo, pwbo,
IDDEFAULT, WBC_REDRAW, (LPARAM)pwbo->pbuffer,
(LPARAM)&rc);
bRet = InvalidateRect(pwbo->hwnd, &rc, TRUE);
// Force an immediate update
if (bNow)
{
bRet = UpdateWindow(pwbo->hwnd);
}
}
}
return bRet;
}
//------------------------------------------- FUNCTIONS PUBLIC TO WINBINDER ONLY
BOOL IsIcon(HANDLE handle)
{
ICONINFO ii;
return GetIconInfo((HICON)handle, &ii);
}
BOOL IsBitmap(HANDLE handle)
{
SIZE siz;
return GetBitmapDimensionEx(handle, &siz);
}
/* Create ImageButton class */
BOOL RegisterImageButtonClass(void)
{
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)ImageButtonProc;
wc.hInstance = hAppInstance;
wc.hbrBackground = NULL;
wc.lpszClassName = IMAGE_BUTTON_CLASS;
wc.lpszMenuName = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = NULL;
wc.cbWndExtra = DLGWINDOWEXTRA;
if (!RegisterClass(&wc))
return FALSE;
wbSetCursor((PWBOBJ)ImageButton, NULL, 0);
return TRUE;
}
/* Associate the tooltip text pszTooltip to control pwbo. If pszTooltip is NULL, create an empty tooltip */
HWND CreateToolTip(PWBOBJ pwbo, LPCTSTR pszTooltip)
{
HWND hwndTT;
TOOLINFO ti;
// Create the ToolTip control.
hwndTT = CreateWindow(TOOLTIPS_CLASS, NULL,
TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
pwbo->hwnd,
NULL, NULL, NULL);
// Create a tool that contains the desired control (pwbo->hwnd)
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = TTF_SUBCLASS;
ti.hwnd = pwbo->hwnd;
ti.uId = 0;
ti.hinst = NULL;
// Get the window text
// ti.lpszText = wbMalloc(256);
if (!pszTooltip || !*pszTooltip)
ti.lpszText = TEXT(""); //'\0';//GetWindowText(pwbo->hwnd, ti.lpszText, 255);
else
ti.lpszText = (LPTSTR)pszTooltip;
// It's not completely clear on the doc: Must have the line below, otherwise the tooltip won't appear.
// The MSDN doc, in the "Messaging and Notification" topic, gets close:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/tooltip/tooltip.asp
// It says "The tool is a control or is defined as a rectangle in the tool's TOOLINFO structure."
// I add: "For controls, the rect member of the TOOLINFO structure must be set to the size of the client area."
GetClientRect(pwbo->hwnd, &ti.rect);
// This does not actually set the control width, it rather instructs it
// to recognize line breaks
SendMessage(hwndTT, TTM_SETMAXTIPWIDTH, 0, 640);
// Add the tool to the control
if (!SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM)&ti))
return NULL;
M_ToolTipWnd = (LONG)hwndTT;
return hwndTT;
}
//------------------------------------------------------------ PRIVATE FUNCTIONS
/*
For opaque bitmaps, set clTransp to NOCOLOR
*/
static BOOL SetTransparentBitmap(HWND hwnd, HBITMAP hbmBits, BOOL bStatic, COLORREF clTransp)
{
// static HBITMAP hbm = NULL, hbmMask;
HBITMAP hbm, hbmMask = NULL, hbmOld;
HDC hdc;
RECT rc;
HBRUSH hbr;
BITMAP bm;
// if(clTransp == NOCOLOR) {
// SendMessage(hwnd, bStatic ? STM_SETIMAGE : BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hbmBits);
// return TRUE;
// }
// Create an empty bitmap the same size as hwnd
GetClientRect(hwnd, &rc);
hbm = wbCreateBitmap(rc.right - rc.left, rc.bottom - rc.top, NULL, NULL);
hdc = wbCreateBitmapDC(hbm);
// Paint hbmBits with a mask
if (clTransp != NOCOLOR)
hbmMask = wbCreateMask(hbmBits, clTransp);
hbr = CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
SelectObject(hdc, hbr);
SelectObject(hdc, GetStockObject(WHITE_PEN));
Rectangle(hdc, 0, 0, rc.right - rc.left, rc.bottom - rc.top);
GetObject(hbmBits, sizeof(BITMAP), (LPVOID)&bm);
if (clTransp == NOCOLOR)
{
wbCopyPartialBits(hdc, hbmBits,
((rc.right - rc.left) - bm.bmWidth) / 2,
((rc.bottom - rc.top) - bm.bmHeight) / 2,
rc.right - rc.left, rc.bottom - rc.top, 0, 0);
}
else
{
wbMaskPartialBits(hdc, hbmBits, hbmMask,
((rc.right - rc.left) - bm.bmWidth) / 2,
((rc.bottom - rc.top) - bm.bmHeight) / 2,
rc.right - rc.left, rc.bottom - rc.top, 0, 0);
}
// Deletes old handle, if any
hbmOld = (HBITMAP)SendMessage(hwnd, bStatic ? STM_SETIMAGE : BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hbm);
if (hbmOld)
DeleteObject(hbmOld);
// Cleanup
DeleteObject(hbr);
// if(hbmMask && (clTransp != NOCOLOR))
if (hbmMask)
DeleteObject(hbmMask);
DeleteDC(hdc);
return TRUE;
}
// Processing routine for Frame controls
static LRESULT CALLBACK FrameProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_SETFOCUS:
case WM_HSCROLL: // For scroll bars
case WM_VSCROLL:
case WM_COMMAND: // Passes commands to parent window
case WM_NOTIFY:
{
HWND hwndParent = GetParent(hwnd);
if (hwndParent)
SendMessage(hwndParent, msg, wParam, lParam);
hCurrentDlg = hwnd;
}
break;
}
return CallWindowProc(lpfnFrameProcOld, hwnd, msg, wParam, lParam);
}
// Processing routine for EditBoxes
static LRESULT CALLBACK EditBoxProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_SETFOCUS:
{
HWND hwndParent = GetParent(hwnd);
if (hwndParent)
SendMessage(hwndParent, WM_SETFOCUS, (WPARAM)hwnd, (LPARAM)wParam);
}
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
HWND hwndParent = GetParent(hwnd);
if (hwndParent)
SendMessage(hwndParent, WBWM_KEYDOWN, (WPARAM)hwnd, (LPARAM)wParam);
}
break;
case WM_KEYUP:
case WM_SYSKEYUP:
{
HWND hwndParent = GetParent(hwnd);
if (hwndParent)
SendMessage(hwndParent, WBWM_KEYUP, (WPARAM)hwnd, (LPARAM)wParam);
}
break;
case WM_SETCURSOR:
{
PWBOBJ pwbo = wbGetWBObj(hwnd);
if (!pwbo)
break;
if (M_nMouseCursor != 0)
{
SetCursor(M_nMouseCursor == -1 ? 0 : (HCURSOR)M_nMouseCursor);
return TRUE; // Must return here, not break
}
else
{
break; // Normal behavior
}
}
break;
}
return CallWindowProc(lpfnEditProcOld, hwnd, msg, wParam, lParam);
}
// Processing routine for InvisibleAreas
static LRESULT CALLBACK InvisibleProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_MOUSEMOVE:
{
PWBOBJ pwbobj = wbGetWBObj(hwnd);
if (!pwbobj)
break;
if (BITTEST(pwbobj->style, WBC_NOTIFY) &&
BITTEST(pwbobj->lparam, WBC_MOUSEMOVE))
{
DWORD dwAlt = (GetKeyState(VK_MENU) < 0) ? WBC_ALT : 0;
if (pwbobj && pwbobj->parent && pwbobj->parent->pszCallBackFn && *pwbobj->parent->pszCallBackFn)
{
//printf("%08X %s\n", pwbobj->lparam, pwbobj->parent->pszCallBackFn);
wbCallUserFunction(pwbobj->parent->pszCallBackFn, pwbobj->pszCallBackObj, pwbobj->parent, pwbobj, pwbobj->id,
WBC_MOUSEMOVE | wParam | dwAlt, lParam, 0);
}
}
}
break;
case WM_SETCURSOR:
{
PWBOBJ pwbo = wbGetWBObj(hwnd);
if (!pwbo)
break;
if (M_nMouseCursor != 0)
{
SetCursor(M_nMouseCursor == -1 ? 0 : (HCURSOR)M_nMouseCursor);
return TRUE; // Must return here, not break
}
else
{
break; // Normal behavior
}
}
break;
}
return CallWindowProc(lpfnInvisibleProcOld, hwnd, msg, wParam, lParam);
}
// Processing routine for ImageButton
static LRESULT CALLBACK ImageButtonProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
PWBOBJ pwbo;
switch (msg)
{
case WM_MOUSEMOVE:
pwbo = wbGetWBObj(hwnd);
{
if (!(wParam & MK_LBUTTON))
{
RECT rc;
POINT pt;
GetWindowRect(hwnd, &rc);
pt.x = LOWORD(lParam) + rc.left;
pt.y = HIWORD(lParam) + rc.top;
if (PtInRect(&rc, pt))
{
SetCapture(hwnd);
InvalidateRect(hwnd, NULL, FALSE);
}
else
{
InvalidateRect(hwnd, NULL, FALSE);
ReleaseCapture();
}
}
if (BITTEST(pwbo->style, WBC_NOTIFY) &&
BITTEST(pwbo->lparam, WBC_MOUSEMOVE))
{
DWORD dwAlt = (GetKeyState(VK_MENU) < 0) ? WBC_ALT : 0;
if (pwbo && pwbo->parent && pwbo->parent->pszCallBackFn && *pwbo->parent->pszCallBackFn)
{
wbCallUserFunction(pwbo->parent->pszCallBackFn, pwbo->pszCallBackObj, pwbo->parent, pwbo, pwbo->id,
WBC_MOUSEMOVE | wParam | dwAlt, lParam, 0);
}
}
}
break;
case WM_LBUTTONDOWN:
pwbo = wbGetWBObj(hwnd);
M_nImageIndex = 2; // Pressed
InvalidateRect(hwnd, NULL, FALSE);
UpdateWindow(hwnd); // Force an update
SetCapture(hwnd);
// Starts the auto-repeat feature
if (pwbo->style & WBC_AUTOREPEAT)
{
// Sets the timer for the first delay
if (pwbo && pwbo->parent && pwbo->parent->pszCallBackFn && *pwbo->parent->pszCallBackFn)
{
wbCallUserFunction(pwbo->parent->pszCallBackFn, pwbo->pszCallBackObj, pwbo->parent, pwbo, pwbo->id, wParam, lParam, 0);
}
M_bRepeatOn = FALSE;
SetTimer(hwnd, REPEAT_TIMER, 400, NULL);
}
break;
case WM_LBUTTONUP:
pwbo = wbGetWBObj(hwnd);
M_nImageIndex = 0; // Released
InvalidateRect(hwnd, NULL, FALSE);
ReleaseCapture();
if (pwbo->style & WBC_AUTOREPEAT)
{
// Kills the timer
KillTimer(hwnd, REPEAT_TIMER);
M_bRepeatOn = FALSE;
}
else if (!(pwbo->style & WBC_DISABLED))
{
if (pwbo && pwbo->parent && pwbo->parent->pszCallBackFn && *pwbo->parent->pszCallBackFn)
{
wbCallUserFunction(pwbo->parent->pszCallBackFn, pwbo->pszCallBackObj, pwbo->parent, pwbo, pwbo->id,
wParam, lParam, 0);
}
}
break;
case WM_PAINT:
{
HDC hdc;
PAINTSTRUCT ps;
HIMAGELIST hi;
RECT rc;
pwbo = wbGetWBObj(hwnd);
if (!pwbo)
break;
if (pwbo->style & WBC_TRANSPARENT)
break;
// ImageList was already stored in control
hi = (HIMAGELIST)M_hiImageList;
if (!hi)
break;
hdc = BeginPaint(hwnd, &ps);
// Select image based on mouse position
// Image index is stored in control
GetWindowRect(hwnd, &rc);
if (pwbo->style & WBC_DISABLED)
{
M_nImageIndex = 3; // Disabled
}
else
{
POINT pt;
GetCursorPos(&pt);
if (PtInRect(&rc, pt))
{
if (M_nImageIndex != 2)
M_nImageIndex = 1;
}
else
{
if (M_bRepeatOn && (pwbo->style & WBC_AUTOREPEAT))
M_nImageIndex = 2;
else
M_nImageIndex = 0;
}
}
ImageList_Draw(hi, M_nImageIndex, hdc, 0, 0, ILD_NORMAL);
EndPaint(hwnd, &ps);
}
return 0;
case WM_TIMER:
pwbo = wbGetWBObj(hwnd);
if ((wParam == REPEAT_TIMER) && (pwbo->style & WBC_AUTOREPEAT))
{
if (pwbo->style & WBC_DISABLED)
{
// Kills the timer
KillTimer(hwnd, REPEAT_TIMER);
}
else
{
if (pwbo && pwbo->parent && pwbo->parent->pszCallBackFn && *pwbo->parent->pszCallBackFn)
{
wbCallUserFunction(pwbo->parent->pszCallBackFn, pwbo->pszCallBackObj, pwbo->parent, pwbo, pwbo->id,
wParam, lParam, 0);
}
if (!M_bRepeatOn)
{
// Starts repeating commands
SetTimer(hwnd, REPEAT_TIMER, 150, NULL);
M_bRepeatOn = TRUE;
}
}
}
break;
case WM_SETCURSOR:
{
pwbo = wbGetWBObj(hwnd);
if (!pwbo)
break;
if (M_nMouseCursor != 0)
{
SetCursor(M_nMouseCursor == -1 ? 0 : (HCURSOR)M_nMouseCursor);
return TRUE; // Must return here, not break
}
else
{
break; // Normal behavior
}
}
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
//------------------------------------------------------------------ END OF FILE
| 22.315331 | 146 | 0.667597 | [
"object"
] |
bd81e1e02338fe516cec0d7c0aef02aeb0309b27 | 837 | h | C | packages/rfw/example/wasm/windows/runner/utils.h | 0xVesion/packages | d0d9eaca2553445e3eb280a9100187bcbb280ac7 | [
"BSD-3-Clause"
] | 5 | 2021-07-19T05:46:35.000Z | 2022-02-15T04:46:11.000Z | packages/rfw/example/wasm/windows/runner/utils.h | 0xVesion/packages | d0d9eaca2553445e3eb280a9100187bcbb280ac7 | [
"BSD-3-Clause"
] | 15 | 2022-02-03T00:29:38.000Z | 2022-02-06T09:20:15.000Z | packages/rfw/example/wasm/windows/runner/utils.h | 0xVesion/packages | d0d9eaca2553445e3eb280a9100187bcbb280ac7 | [
"BSD-3-Clause"
] | 5 | 2021-10-15T03:22:42.000Z | 2022-03-08T13:23:05.000Z | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
| 34.875 | 79 | 0.759857 | [
"vector"
] |
bd828382347ffe28e5c7f7d37464157247e6f0cd | 75,848 | c | C | source/adios2/toolkit/sst/cp/ffs_marshal.c | CompFUSE/ADIOS2 | 2f5afc53b63b3bddd86e0f0d1eee60c7ab002a1b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | source/adios2/toolkit/sst/cp/ffs_marshal.c | CompFUSE/ADIOS2 | 2f5afc53b63b3bddd86e0f0d1eee60c7ab002a1b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | source/adios2/toolkit/sst/cp/ffs_marshal.c | CompFUSE/ADIOS2 | 2f5afc53b63b3bddd86e0f0d1eee60c7ab002a1b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-04-14T13:32:45.000Z | 2020-04-14T13:32:45.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "adios2/common/ADIOSConfig.h"
#include <atl.h>
#include <evpath.h>
#include <pthread.h>
#include "adios2/common/ADIOSConfig.h"
#include "sst.h"
#include "adios2/toolkit/profiling/taustubs/taustubs.h"
#include "cp_internal.h"
#include "ffs_marshal.h"
typedef struct dcomplex
{
double real_part;
double imag_part;
} dcomplex_struct;
typedef struct fcomplex
{
float real_part;
float imag_part;
} fcomplex_struct;
FMField fcomplex_field_list[] = {
{"real", "float", sizeof(float), FMOffset(fcomplex_struct *, real_part)},
{"imag", "float", sizeof(float), FMOffset(fcomplex_struct *, imag_part)},
{NULL, NULL, 0, 0}};
FMField dcomplex_field_list[] = {
{"real", "float", sizeof(double), FMOffset(dcomplex_struct *, real_part)},
{"imag", "float", sizeof(double), FMOffset(dcomplex_struct *, imag_part)},
{NULL, NULL, 0, 0}};
static char *ConcatName(const char *base_name, const char *postfix)
{
char *Ret =
malloc(strlen("SST_") + strlen(base_name) + strlen(postfix) + 1);
strcpy(Ret, "SST_");
strcat(Ret, base_name);
strcat(Ret, postfix);
return Ret;
}
static char *BuildVarName(const char *base_name, const char *type,
const int element_size)
{
int Len = strlen(base_name) + strlen(type) + strlen("SST_") + 16;
char *Ret = malloc(Len);
sprintf(Ret, "SST%d_%d_", element_size, (int)strlen(type));
strcat(Ret, type);
strcat(Ret, "_");
strcat(Ret, base_name);
return Ret;
}
static void BreakdownVarName(const char *Name, char **base_name_p,
char **type_p, int *element_size_p)
{
int TypeLen;
int ElementSize;
const char *NameStart;
char *TypeStart = strchr(Name, '_') + 1;
TypeStart = strchr(TypeStart, '_') + 1;
sscanf(Name, "SST%d_%d_", &ElementSize, &TypeLen);
NameStart = TypeStart + TypeLen + 1;
*element_size_p = ElementSize;
*type_p = malloc(TypeLen + 1);
strncpy(*type_p, TypeStart, TypeLen);
(*type_p)[TypeLen] = 0;
*base_name_p = strdup(NameStart);
}
static char *BuildArrayName(const char *base_name, const char *type,
const int element_size)
{
int Len = strlen(base_name) + strlen(type) + strlen("SST_") + 16;
char *Ret = malloc(Len);
sprintf(Ret, "SST%d_%d_", element_size, (int)strlen(type));
strcat(Ret, type);
strcat(Ret, "_");
strcat(Ret, base_name);
strcat(Ret, "Dims");
return Ret;
}
static void BreakdownArrayName(const char *Name, char **base_name_p,
char **type_p, int *element_size_p)
{
int TypeLen;
int ElementSize;
const char *NameStart;
char *TypeStart = strchr(Name, '_') + 1;
TypeStart = strchr(TypeStart, '_') + 1;
sscanf(Name, "SST%d_%d_", &ElementSize, &TypeLen);
NameStart = TypeStart + TypeLen + 1;
*element_size_p = ElementSize;
*type_p = malloc(TypeLen + 1);
strncpy(*type_p, TypeStart, TypeLen);
(*type_p)[TypeLen] = 0;
*base_name_p = strdup(NameStart);
(*base_name_p)[strlen(*base_name_p) - 4] = 0; // kill "Dims"
}
static char *TranslateADIOS2Type2FFS(const char *Type)
{
if (strcmp(Type, "char") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "signed char") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "unsigned char") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "short") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "unsigned short") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "int") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "unsigned int") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "long int") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "long long int") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "unsigned long int") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "unsigned long long int") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "float") == 0)
{
return strdup("float");
}
else if (strcmp(Type, "double") == 0)
{
return strdup("float");
}
else if (strcmp(Type, "long double") == 0)
{
return strdup("float");
}
else if (strcmp(Type, "float complex") == 0)
{
return strdup("complex4");
}
else if (strcmp(Type, "double complex") == 0)
{
return strdup("complex8");
}
else if (strcmp(Type, "int8_t") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "int16_t") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "int32_t") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "int64_t") == 0)
{
return strdup("integer");
}
else if (strcmp(Type, "uint8_t") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "uint16_t") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "uint32_t") == 0)
{
return strdup("unsigned integer");
}
else if (strcmp(Type, "uint64_t") == 0)
{
return strdup("unsigned integer");
}
return strdup(Type);
}
static char *TranslateFFSType2ADIOS(const char *Type, int size)
{
if (strcmp(Type, "integer") == 0)
{
if (size == 1)
{
return strdup("int8_t");
}
else if (size == 2)
{
return strdup("int16_t");
}
else if (size == 4)
{
return strdup("int32_t");
}
else if (size == 8)
{
return strdup("int64_t");
}
}
else if (strcmp(Type, "unsigned integer") == 0)
{
if (size == 1)
{
return strdup("uint8_t");
}
else if (size == 2)
{
return strdup("uint16_t");
}
else if (size == 4)
{
return strdup("uint32_t");
}
else if (size == 8)
{
return strdup("uint64_t");
}
}
else if ((strcmp(Type, "double") == 0) || (strcmp(Type, "float") == 0))
{
if (size == sizeof(float))
{
return strdup("float");
}
else if ((sizeof(long double) != sizeof(double)) &&
(size == sizeof(long double)))
{
return strdup("long double");
}
else
{
return strdup("double");
}
}
else if (strcmp(Type, "complex4") == 0)
{
return strdup("float complex");
}
else if (strcmp(Type, "complex8") == 0)
{
return strdup("double complex");
}
return strdup(Type);
}
static void RecalcMarshalStorageSize(SstStream Stream)
{
struct FFSWriterMarshalBase *Info = Stream->WriterMarshalData;
if (Info->DataFieldCount)
{
FMFieldList LastDataField;
size_t NewDataSize;
LastDataField = &Info->DataFields[Info->DataFieldCount - 1];
NewDataSize =
(LastDataField->field_offset + LastDataField->field_size + 7) & ~7;
Stream->D = realloc(Stream->D, NewDataSize + 8);
memset(Stream->D + Stream->DataSize, 0, NewDataSize - Stream->DataSize);
Stream->DataSize = NewDataSize;
}
if (Info->MetaFieldCount)
{
FMFieldList LastMetaField;
size_t NewMetaSize;
LastMetaField = &Info->MetaFields[Info->MetaFieldCount - 1];
NewMetaSize =
(LastMetaField->field_offset + LastMetaField->field_size + 7) & ~7;
Stream->M = realloc(Stream->M, NewMetaSize + 8);
memset(Stream->M + Stream->MetadataSize, 0,
NewMetaSize - Stream->MetadataSize);
Stream->MetadataSize = NewMetaSize;
}
}
static void RecalcAttributeStorageSize(SstStream Stream)
{
struct FFSWriterMarshalBase *Info = Stream->WriterMarshalData;
if (Info->AttributeFieldCount)
{
FMFieldList LastAttributeField;
size_t NewAttributeSize;
LastAttributeField =
&Info->AttributeFields[Info->AttributeFieldCount - 1];
NewAttributeSize = (LastAttributeField->field_offset +
LastAttributeField->field_size + 7) &
~7;
Info->AttributeData =
realloc(Info->AttributeData, NewAttributeSize + 8);
memset(Info->AttributeData + Info->AttributeSize, 0,
NewAttributeSize - Info->AttributeSize);
Info->AttributeSize = NewAttributeSize;
}
}
static void AddSimpleField(FMFieldList *FieldP, int *CountP, const char *Name,
const char *Type, int ElementSize)
{
int Offset = 0;
FMFieldList Field;
if (*CountP)
{
FMFieldList PriorField;
PriorField = &((*FieldP)[(*CountP) - 1]);
int PriorFieldSize = PriorField->field_size;
if (strchr(PriorField->field_type, '['))
{
// really a pointer
PriorFieldSize = sizeof(void *);
}
Offset =
((PriorField->field_offset + PriorFieldSize + ElementSize - 1) /
ElementSize) *
ElementSize;
}
if (*FieldP)
*FieldP = realloc(*FieldP, (*CountP + 2) * sizeof((*FieldP)[0]));
else
*FieldP = malloc((*CountP + 2) * sizeof((*FieldP)[0]));
Field = &((*FieldP)[*CountP]);
(*CountP)++;
Field->field_name = strdup(Name);
Field->field_type = strdup(Type);
Field->field_size = ElementSize;
Field->field_offset = Offset;
Field++;
Field->field_name = NULL;
Field->field_type = NULL;
Field->field_size = 0;
Field->field_offset = 0;
}
static void AddField(FMFieldList *FieldP, int *CountP, const char *Name,
const char *Type, int ElementSize)
{
char *TransType = TranslateADIOS2Type2FFS(Type);
AddSimpleField(FieldP, CountP, Name, TransType, ElementSize);
free(TransType);
}
static void AddFixedArrayField(FMFieldList *FieldP, int *CountP,
const char *Name, const char *Type,
int ElementSize, int DimCount)
{
const char *TransType = TranslateADIOS2Type2FFS(Type);
char *TypeWithArray = malloc(strlen(TransType) + 16);
sprintf(TypeWithArray, "*(%s[%d])", TransType, DimCount);
free((void *)TransType);
AddSimpleField(FieldP, CountP, Name, TypeWithArray, sizeof(void *));
free(TypeWithArray);
(*FieldP)[*CountP - 1].field_size = ElementSize;
}
static void AddVarArrayField(FMFieldList *FieldP, int *CountP, const char *Name,
const char *Type, int ElementSize, char *SizeField)
{
char *TransType = TranslateADIOS2Type2FFS(Type);
char *TypeWithArray = malloc(strlen(TransType) + strlen(SizeField) + 8);
sprintf(TypeWithArray, "%s[%s]", TransType, SizeField);
free(TransType);
AddSimpleField(FieldP, CountP, Name, TypeWithArray, sizeof(void *));
free(TypeWithArray);
(*FieldP)[*CountP - 1].field_size = ElementSize;
}
struct FFSMetadataInfoStruct
{
size_t BitFieldCount;
size_t *BitField;
size_t DataBlockSize;
};
static int FFSBitfieldTest(struct FFSMetadataInfoStruct *MBase, int Bit);
static void InitMarshalData(SstStream Stream)
{
struct FFSWriterMarshalBase *Info =
malloc(sizeof(struct FFSWriterMarshalBase));
struct FFSMetadataInfoStruct *MBase;
memset(Info, 0, sizeof(*Info));
Stream->WriterMarshalData = Info;
Info->RecCount = 0;
Info->RecList = malloc(sizeof(Info->RecList[0]));
Info->MetaFieldCount = 0;
Info->MetaFields = NULL;
Info->DataFieldCount = 0;
Info->DataFields = NULL;
Info->LocalFMContext = create_local_FMcontext();
AddSimpleField(&Info->MetaFields, &Info->MetaFieldCount, "BitFieldCount",
"integer", sizeof(size_t));
AddSimpleField(&Info->MetaFields, &Info->MetaFieldCount, "BitField",
"integer[BitFieldCount]", sizeof(size_t));
AddSimpleField(&Info->MetaFields, &Info->MetaFieldCount, "DataBlockSize",
"integer", sizeof(size_t));
RecalcMarshalStorageSize(Stream);
MBase = Stream->M;
MBase->BitFieldCount = 0;
MBase->BitField = malloc(sizeof(size_t));
MBase->DataBlockSize = 0;
}
extern void FFSFreeMarshalData(SstStream Stream)
{
if (Stream->Role == WriterRole)
{
/* writer side */
struct FFSWriterMarshalBase *Info =
(struct FFSWriterMarshalBase *)Stream->WriterMarshalData;
struct FFSMetadataInfoStruct *MBase;
MBase = Stream->M;
for (int i = 0; i < Info->RecCount; i++)
{
free(Info->RecList[i].Type);
}
if (Info->RecList)
free(Info->RecList);
if (Info->MetaFieldCount)
free_FMfield_list(Info->MetaFields);
if (Info->DataFieldCount)
free_FMfield_list(Info->DataFields);
if (Info->LocalFMContext)
free_FMcontext(Info->LocalFMContext);
free(Info);
Stream->WriterMarshalData = NULL;
free(Stream->D);
Stream->D = NULL;
free(MBase->BitField);
free(Stream->M);
Stream->M = NULL;
}
else
{
/* reader side */
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
if (Info)
{
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (Info->WriterInfo[i].RawBuffer)
free(Info->WriterInfo[i].RawBuffer);
}
if (Info->WriterInfo)
free(Info->WriterInfo);
if (Info->MetadataBaseAddrs)
free(Info->MetadataBaseAddrs);
if (Info->MetadataFieldLists)
free(Info->MetadataFieldLists);
if (Info->DataBaseAddrs)
free(Info->DataBaseAddrs);
if (Info->DataFieldLists)
free(Info->DataFieldLists);
for (int i = 0; i < Info->VarCount; i++)
{
free(Info->VarList[i].VarName);
free(Info->VarList[i].PerWriterMetaFieldDesc);
free(Info->VarList[i].PerWriterDataFieldDesc);
free(Info->VarList[i].PerWriterStart);
free(Info->VarList[i].PerWriterCounts);
free(Info->VarList[i].PerWriterIncomingData);
free(Info->VarList[i].PerWriterIncomingSize);
}
if (Info->VarList)
free(Info->VarList);
free(Info);
Stream->ReaderMarshalData = NULL;
}
}
}
#if !defined(ADIOS2_HAVE_ZFP)
#define ZFPcompressionPossible(Type, DimCount) ((void)Type, 0)
#endif
static FFSWriterRec CreateWriterRec(SstStream Stream, void *Variable,
const char *Name, const char *Type,
size_t ElemSize, size_t DimCount)
{
if (!Stream->WriterMarshalData)
{
InitMarshalData(Stream);
}
struct FFSWriterMarshalBase *Info =
(struct FFSWriterMarshalBase *)Stream->WriterMarshalData;
Info->RecList =
realloc(Info->RecList, (Info->RecCount + 1) * sizeof(Info->RecList[0]));
FFSWriterRec Rec = &Info->RecList[Info->RecCount];
Rec->Key = Variable;
Rec->FieldID = Info->RecCount;
Rec->DimCount = DimCount;
Rec->Type = strdup(Type);
if (DimCount == 0)
{
// simple field, only add base value FMField to metadata
char *SstName = ConcatName(Name, "");
AddField(&Info->MetaFields, &Info->MetaFieldCount, SstName, Type,
ElemSize);
free(SstName);
RecalcMarshalStorageSize(Stream);
Rec->MetaOffset =
Info->MetaFields[Info->MetaFieldCount - 1].field_offset;
Rec->DataOffset = (size_t)-1;
// Changing the formats renders these invalid
Info->MetaFormat = NULL;
}
else
{
// Array field. To Metadata, add FMFields for DimCount, Shape, Count
// and Offsets matching _MetaArrayRec
char *ArrayName = BuildArrayName(Name, Type, ElemSize);
AddField(&Info->MetaFields, &Info->MetaFieldCount, ArrayName, "integer",
sizeof(size_t));
free(ArrayName);
Rec->MetaOffset =
Info->MetaFields[Info->MetaFieldCount - 1].field_offset;
char *ShapeName = ConcatName(Name, "Shape");
char *CountName = ConcatName(Name, "Count");
char *OffsetsName = ConcatName(Name, "Offsets");
AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount, ShapeName,
"integer", sizeof(size_t), DimCount);
AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount, CountName,
"integer", sizeof(size_t), DimCount);
AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount,
OffsetsName, "integer", sizeof(size_t), DimCount);
free(ShapeName);
free(CountName);
free(OffsetsName);
RecalcMarshalStorageSize(Stream);
if ((Stream->ConfigParams->CompressionMethod == SstCompressZFP) &&
ZFPcompressionPossible(Type, DimCount))
{
Type = "char";
ElemSize = 1;
}
// To Data, add FMFields for ElemCount and Array matching _ArrayRec
char *ElemCountName = ConcatName(Name, "ElemCount");
AddField(&Info->DataFields, &Info->DataFieldCount, ElemCountName,
"integer", sizeof(size_t));
Rec->DataOffset =
Info->DataFields[Info->DataFieldCount - 1].field_offset;
char *SstName = ConcatName(Name, "");
AddVarArrayField(&Info->DataFields, &Info->DataFieldCount, SstName,
Type, ElemSize, ElemCountName);
free(SstName);
free(ElemCountName);
RecalcMarshalStorageSize(Stream);
// Changing the formats renders these invalid
Info->MetaFormat = NULL;
Info->DataFormat = NULL;
}
Info->RecCount++;
return Rec;
}
typedef struct _ArrayRec
{
size_t ElemCount;
void *Array;
} ArrayRec;
typedef struct _MetaArrayRec
{
size_t Dims;
size_t *Shape;
size_t *Count;
size_t *Offsets;
} MetaArrayRec;
typedef struct _FFSTimestepInfo
{
FFSBuffer MetaEncodeBuffer;
FFSBuffer DataEncodeBuffer;
} * FFSTimestepInfo;
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define NO_SANITIZE_THREAD __attribute__((no_sanitize("thread")))
#endif
#endif
#ifndef NO_SANITIZE_THREAD
#define NO_SANITIZE_THREAD
#endif
/*
* The FFS-encoded data buffer is created and destroyed at the control
* plane level, moderated by CP stream locking. But between times it
* is passed to the data plane for servicing incoming read requests,
* where it is managed by DP-level locking. TSAN sees fault with this
* because the buffer is accessed and written (freed) under different
* locking stragegies. To suppress TSAN errors, we're telling TSAN to
* ignore the free.
*/
static inline void NO_SANITIZE_THREAD no_tsan_free_FFSBuffer(FFSBuffer buf)
{
free_FFSBuffer(buf);
}
static void FreeTSInfo(void *ClientData)
{
FFSTimestepInfo TSInfo = (FFSTimestepInfo)ClientData;
if (TSInfo->MetaEncodeBuffer)
free_FFSBuffer(TSInfo->MetaEncodeBuffer);
if (TSInfo->DataEncodeBuffer)
no_tsan_free_FFSBuffer(TSInfo->DataEncodeBuffer);
free(TSInfo);
}
static void FreeAttrInfo(void *ClientData)
{
free_FFSBuffer((FFSBuffer)ClientData);
}
static size_t *CopyDims(const size_t Count, const size_t *Vals)
{
size_t *Ret = malloc(Count * sizeof(Ret[0]));
memcpy(Ret, Vals, Count * sizeof(Ret[0]));
return Ret;
}
static size_t CalcSize(const size_t Count, const size_t *Vals)
{
size_t i;
size_t Elems = 1;
for (i = 0; i < Count; i++)
{
Elems *= Vals[i];
}
return Elems;
}
static FFSWriterRec LookupWriterRec(SstStream Stream, void *Key)
{
struct FFSWriterMarshalBase *Info = Stream->WriterMarshalData;
if (!Stream->WriterMarshalData)
return NULL;
for (int i = 0; i < Info->RecCount; i++)
{
if (Info->RecList[i].Key == Key)
{
return &Info->RecList[i];
}
}
return NULL;
}
static FFSVarRec LookupVarByKey(SstStream Stream, void *Key)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
for (int i = 0; i < Info->VarCount; i++)
{
if (Info->VarList[i].Variable == Key)
{
return &Info->VarList[i];
}
}
return NULL;
}
static FFSVarRec LookupVarByName(SstStream Stream, const char *Name)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
for (int i = 0; i < Info->VarCount; i++)
{
if (strcmp(Info->VarList[i].VarName, Name) == 0)
{
return &Info->VarList[i];
}
}
return NULL;
}
static FFSVarRec CreateVarRec(SstStream Stream, const char *ArrayName)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
Info->VarList =
realloc(Info->VarList, sizeof(Info->VarList[0]) * (Info->VarCount + 1));
memset(&Info->VarList[Info->VarCount], 0, sizeof(Info->VarList[0]));
Info->VarList[Info->VarCount].VarName = strdup(ArrayName);
Info->VarList[Info->VarCount].PerWriterMetaFieldDesc =
calloc(sizeof(FMFieldList), Stream->WriterCohortSize);
Info->VarList[Info->VarCount].PerWriterDataFieldDesc =
calloc(sizeof(FMFieldList), Stream->WriterCohortSize);
Info->VarList[Info->VarCount].PerWriterStart =
calloc(sizeof(size_t *), Stream->WriterCohortSize);
Info->VarList[Info->VarCount].PerWriterCounts =
calloc(sizeof(size_t *), Stream->WriterCohortSize);
Info->VarList[Info->VarCount].PerWriterIncomingData =
calloc(sizeof(void *), Stream->WriterCohortSize);
Info->VarList[Info->VarCount].PerWriterIncomingSize =
calloc(sizeof(size_t), Stream->WriterCohortSize);
return &Info->VarList[Info->VarCount++];
}
extern void CP_verbose(SstStream Stream, char *Format, ...);
extern int SstFFSWriterBeginStep(SstStream Stream, int mode,
const float timeout_sec)
{
return 0;
}
void SstReaderInitFFSCallback(SstStream Stream, void *Reader,
VarSetupUpcallFunc VarCallback,
ArraySetupUpcallFunc ArrayCallback,
AttrSetupUpcallFunc AttrCallback,
ArrayBlocksInfoUpcallFunc BlocksInfoCallback)
{
Stream->VarSetupUpcall = VarCallback;
Stream->ArraySetupUpcall = ArrayCallback;
Stream->AttrSetupUpcall = AttrCallback;
Stream->ArrayBlocksInfoUpcall = BlocksInfoCallback;
Stream->SetupUpcallReader = Reader;
}
extern void SstFFSGetDeferred(SstStream Stream, void *Variable,
const char *Name, size_t DimCount,
const size_t *Start, const size_t *Count,
void *Data)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
int GetFromWriter = 0;
FFSVarRec Var = LookupVarByKey(Stream, Variable);
// if Variable is in Metadata (I.E. DimCount == 0), move incoming data to
// Data area
if (DimCount == 0)
{
void *IncomingDataBase =
((char *)Info->MetadataBaseAddrs[GetFromWriter]) +
Var->PerWriterMetaFieldDesc[GetFromWriter]->field_offset;
memcpy(Data, IncomingDataBase,
Var->PerWriterMetaFieldDesc[GetFromWriter]->field_size);
}
else
{
// Build request structure and enter it into requests list
FFSArrayRequest Req = malloc(sizeof(*Req));
Req->VarRec = Var;
Req->RequestType = Global;
// make a copy of Start and Count request
Req->Start = malloc(sizeof(Start[0]) * Var->DimCount);
memcpy(Req->Start, Start, sizeof(Start[0]) * Var->DimCount);
Req->Count = malloc(sizeof(Count[0]) * Var->DimCount);
memcpy(Req->Count, Count, sizeof(Count[0]) * Var->DimCount);
Req->Data = Data;
Req->Next = Info->PendingVarRequests;
Info->PendingVarRequests = Req;
}
}
extern void SstFFSGetLocalDeferred(SstStream Stream, void *Variable,
const char *Name, size_t DimCount,
const int BlockID, const size_t *Count,
void *Data)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
int GetFromWriter = 0;
FFSVarRec Var = LookupVarByKey(Stream, Variable);
// if Variable is in Metadata (I.E. DimCount == 0), move incoming data to
// Data area
if (DimCount == 0)
{
void *IncomingDataBase =
((char *)Info->MetadataBaseAddrs[GetFromWriter]) +
Var->PerWriterMetaFieldDesc[GetFromWriter]->field_offset;
memcpy(Data, IncomingDataBase,
Var->PerWriterMetaFieldDesc[GetFromWriter]->field_size);
}
else
{
// Build request structure and enter it into requests list
FFSArrayRequest Req = malloc(sizeof(*Req));
memset(Req, 0, sizeof(*Req));
Req->VarRec = Var;
Req->RequestType = Local;
Req->NodeID = BlockID;
// make a copy of Count request
Req->Count = malloc(sizeof(Count[0]) * Var->DimCount);
memcpy(Req->Count, Count, sizeof(Count[0]) * Var->DimCount);
Req->Data = Data;
Req->Next = Info->PendingVarRequests;
Info->PendingVarRequests = Req;
}
}
static int NeedWriter(FFSArrayRequest Req, int i)
{
if (Req->RequestType == Local)
{
return (Req->NodeID == i);
}
// else Global case
for (int j = 0; j < Req->VarRec->DimCount; j++)
{
size_t SelOffset = Req->Start[j];
size_t SelSize = Req->Count[j];
size_t RankOffset;
size_t RankSize;
if (Req->VarRec->PerWriterStart[i] == NULL)
/* this writer didn't write */
{
return 0;
}
RankOffset = Req->VarRec->PerWriterStart[i][j];
RankSize = Req->VarRec->PerWriterCounts[i][j];
if ((SelSize == 0) || (RankSize == 0))
{
return 0;
}
if ((RankOffset < SelOffset && (RankOffset + RankSize) <= SelOffset) ||
(RankOffset >= SelOffset + SelSize))
{
return 0;
}
}
return 1;
}
static void IssueReadRequests(SstStream Stream, FFSArrayRequest Reqs)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
SstFullMetadata Mdata = Stream->CurrentMetadata;
while (Reqs)
{
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (NeedWriter(Reqs, i))
{
Info->WriterInfo[i].Status = Needed;
}
}
Reqs = Reqs->Next;
}
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (Info->WriterInfo[i].Status == Needed)
{
size_t DataSize =
((struct FFSMetadataInfoStruct *)Info->MetadataBaseAddrs[i])
->DataBlockSize;
void *DP_TimestepInfo =
Mdata->DP_TimestepInfo ? Mdata->DP_TimestepInfo[i] : NULL;
Info->WriterInfo[i].RawBuffer =
realloc(Info->WriterInfo[i].RawBuffer, DataSize);
char tmpstr[256] = {0};
sprintf(tmpstr, "Request to rank %d, bytes", i);
TAU_SAMPLE_COUNTER(tmpstr, (double)DataSize);
Info->WriterInfo[i].ReadHandle = SstReadRemoteMemory(
Stream, i, Stream->ReaderTimestep, 0, DataSize,
Info->WriterInfo[i].RawBuffer, DP_TimestepInfo);
Info->WriterInfo[i].Status = Requested;
}
}
}
static void ClearReadRequests(SstStream Stream)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
FFSArrayRequest Req = Info->PendingVarRequests;
while (Req)
{
FFSArrayRequest PrevReq = Req;
Req = Req->Next;
free(PrevReq->Count);
free(PrevReq->Start);
free(PrevReq);
}
Info->PendingVarRequests = NULL;
}
static void DecodeAndPrepareData(SstStream Stream, int Writer)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
FFSReaderPerWriterRec *WriterInfo = &Info->WriterInfo[Writer];
FFSTypeHandle FFSformat;
FMFieldList FieldList;
FMStructDescList FormatList;
void *BaseData;
int DumpData = -1;
FFSformat = FFSTypeHandle_from_encode(Stream->ReaderFFSContext,
WriterInfo->RawBuffer);
if (!FFShas_conversion(FFSformat))
{
FMContext FMC = FMContext_from_FFS(Stream->ReaderFFSContext);
FMFormat Format = FMformat_from_ID(FMC, WriterInfo->RawBuffer);
FMStructDescList List =
FMcopy_struct_list(format_list_of_FMFormat(Format));
FMlocalize_structs(List);
establish_conversion(Stream->ReaderFFSContext, FFSformat, List);
FMfree_struct_list(List);
}
if (FFSdecode_in_place_possible(FFSformat))
{
FFSdecode_in_place(Stream->ReaderFFSContext, WriterInfo->RawBuffer,
&BaseData);
}
else
{
size_t DataSize =
((struct FFSMetadataInfoStruct *)Info->MetadataBaseAddrs[Writer])
->DataBlockSize;
int DecodedLength = FFS_est_decode_length(
Stream->ReaderFFSContext, WriterInfo->RawBuffer, DataSize);
BaseData = malloc(DecodedLength);
FFSBuffer decode_buf = create_fixed_FFSBuffer(BaseData, DecodedLength);
FFSdecode_to_buffer(Stream->ReaderFFSContext, WriterInfo->RawBuffer,
decode_buf);
}
if (DumpData == -1)
{
DumpData = (getenv("SstDumpData") != NULL);
}
if (DumpData)
{
printf("\nOn Rank %d, IncomingDatablock from writer %d is %p :\n",
Stream->Rank, Writer, BaseData);
FMdump_data(FMFormat_of_original(FFSformat), BaseData, 1024000);
}
Info->DataBaseAddrs[Writer] = BaseData;
FormatList = format_list_of_FMFormat(FMFormat_of_original(FFSformat));
FieldList = FormatList[0].field_list;
Info->DataFieldLists[Writer] = FieldList;
int i = 0;
while (FieldList[i].field_name)
{
ArrayRec *data_base =
(ArrayRec *)((char *)BaseData + FieldList[i].field_offset);
const char *ArrayName = FieldList[i + 1].field_name + 4;
FFSVarRec VarRec = LookupVarByName(Stream, ArrayName);
if (VarRec)
{
VarRec->PerWriterIncomingData[Writer] = data_base->Array;
VarRec->PerWriterIncomingSize[Writer] = data_base->ElemCount;
VarRec->PerWriterDataFieldDesc[Writer] = &FieldList[i + 1];
}
i += 2;
}
}
static SstStatusValue WaitForReadRequests(SstStream Stream)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (Info->WriterInfo[i].Status == Requested)
{
SstStatusValue Result =
SstWaitForCompletion(Stream, Info->WriterInfo[i].ReadHandle);
if (Result == SstSuccess)
{
Info->WriterInfo[i].Status = Full;
DecodeAndPrepareData(Stream, i);
}
else
{
CP_verbose(Stream, "Wait for remote read completion failed, "
"returning failure\n");
return Result;
}
}
}
CP_verbose(Stream, "All remote memory reads completed\n");
return SstSuccess;
}
#ifdef NOTUSED
static void MapLocalToGlobalIndex(size_t Dims, const size_t *LocalIndex,
const size_t *LocalOffsets,
size_t *GlobalIndex)
{
for (int i = 0; i < Dims; i++)
{
GlobalIndex[i] = LocalIndex[i] + LocalOffsets[i];
}
}
#endif
static void MapGlobalToLocalIndex(size_t Dims, const size_t *GlobalIndex,
const size_t *LocalOffsets,
size_t *LocalIndex)
{
for (int i = 0; i < Dims; i++)
{
LocalIndex[i] = GlobalIndex[i] - LocalOffsets[i];
}
}
static int FindOffset(size_t Dims, const size_t *Size, const size_t *Index)
{
int Offset = 0;
for (int i = 0; i < Dims; i++)
{
Offset = Index[i] + (Size[i] * Offset);
}
return Offset;
}
static int FindOffsetCM(size_t Dims, const size_t *Size, const size_t *Index)
{
int Offset = 0;
for (int i = Dims - 1; i >= 0; i--)
{
Offset = Index[i] + (Size[i] * Offset);
}
return Offset;
}
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
/*
* - ElementSize is the byte size of the array elements
* - Dims is the number of dimensions in the variable
* - GlobalDims is an array, Dims long, giving the size of each dimension
* - PartialOffsets is an array, Dims long, giving the starting offsets per
* dimension of this data block in the global array
* - PartialCounts is an array, Dims long, giving the size per dimension
* of this data block in the global array
* - SelectionOffsets is an array, Dims long, giving the starting offsets in
* the
* global array of the output selection.
* - SelectionCounts is an array, Dims long, giving the size per dimension
* of the output selection.
* - InData is the input, a slab of the global array
* - OutData is the output, to be filled with the selection array.
*/
// Row major version
void ExtractSelectionFromPartialRM(int ElementSize, size_t Dims,
const size_t *GlobalDims,
const size_t *PartialOffsets,
const size_t *PartialCounts,
const size_t *SelectionOffsets,
const size_t *SelectionCounts,
const char *InData, char *OutData)
{
size_t BlockSize;
size_t SourceBlockStride = 0;
size_t DestBlockStride = 0;
size_t SourceBlockStartOffset;
size_t DestBlockStartOffset;
size_t BlockCount;
size_t OperantDims;
size_t OperantElementSize;
BlockSize = 1;
OperantDims = Dims;
OperantElementSize = ElementSize;
for (int Dim = Dims - 1; Dim >= 0; Dim--)
{
if ((GlobalDims[Dim] == PartialCounts[Dim]) &&
(SelectionCounts[Dim] == PartialCounts[Dim]))
{
BlockSize *= GlobalDims[Dim];
OperantDims--; /* last dimension doesn't matter, we got all and we
want all */
OperantElementSize *= GlobalDims[Dim];
}
else
{
size_t Left = MAX(PartialOffsets[Dim], SelectionOffsets[Dim]);
size_t Right = MIN(PartialOffsets[Dim] + PartialCounts[Dim],
SelectionOffsets[Dim] + SelectionCounts[Dim]);
BlockSize *= (Right - Left);
break;
}
}
if (OperantDims > 0)
{
SourceBlockStride = PartialCounts[OperantDims - 1] * OperantElementSize;
DestBlockStride = SelectionCounts[OperantDims - 1] * OperantElementSize;
}
/* calculate first selected element and count */
BlockCount = 1;
size_t *FirstIndex = malloc(Dims * sizeof(FirstIndex[0]));
for (int Dim = 0; Dim < Dims; Dim++)
{
size_t Left = MAX(PartialOffsets[Dim], SelectionOffsets[Dim]);
size_t Right = MIN(PartialOffsets[Dim] + PartialCounts[Dim],
SelectionOffsets[Dim] + SelectionCounts[Dim]);
if (Dim < OperantDims - 1)
{
BlockCount *= (Right - Left);
}
FirstIndex[Dim] = Left;
}
size_t *SelectionIndex = malloc(Dims * sizeof(SelectionIndex[0]));
MapGlobalToLocalIndex(Dims, FirstIndex, SelectionOffsets, SelectionIndex);
DestBlockStartOffset = FindOffset(Dims, SelectionCounts, SelectionIndex);
free(SelectionIndex);
DestBlockStartOffset *= ElementSize;
size_t *PartialIndex = malloc(Dims * sizeof(PartialIndex[0]));
MapGlobalToLocalIndex(Dims, FirstIndex, PartialOffsets, PartialIndex);
SourceBlockStartOffset = FindOffset(Dims, PartialCounts, PartialIndex);
free(PartialIndex);
SourceBlockStartOffset *= ElementSize;
InData += SourceBlockStartOffset;
OutData += DestBlockStartOffset;
size_t i;
for (i = 0; i < BlockCount; i++)
{
memcpy(OutData, InData, BlockSize * ElementSize);
InData += SourceBlockStride;
OutData += DestBlockStride;
}
free(FirstIndex);
}
static void ReverseDimensions(size_t *Dimensions, int count)
{
for (int i = 0; i < count / 2; i++)
{
size_t tmp = Dimensions[i];
Dimensions[i] = Dimensions[count - i - 1];
Dimensions[count - i - 1] = tmp;
}
}
// Column-major version
void ExtractSelectionFromPartialCM(int ElementSize, size_t Dims,
const size_t *GlobalDims,
const size_t *PartialOffsets,
const size_t *PartialCounts,
const size_t *SelectionOffsets,
const size_t *SelectionCounts,
const char *InData, char *OutData)
{
int BlockSize;
int SourceBlockStride = 0;
int DestBlockStride = 0;
int SourceBlockStartOffset;
int DestBlockStartOffset;
int BlockCount;
int OperantElementSize;
BlockSize = 1;
OperantElementSize = ElementSize;
for (int Dim = 0; Dim < Dims; Dim++)
{
if ((GlobalDims[Dim] == PartialCounts[Dim]) &&
(SelectionCounts[Dim] == PartialCounts[Dim]))
{
BlockSize *= GlobalDims[Dim];
OperantElementSize *= GlobalDims[Dim];
/* skip the first bit of everything */
GlobalDims++;
PartialOffsets++;
PartialCounts++;
SelectionOffsets++;
SelectionCounts++;
Dims--;
/* and make sure we do the next dimensions appropriately by
* repeating this iterator value */
Dim--;
}
else
{
int Left = MAX(PartialOffsets[Dim], SelectionOffsets[Dim]);
int Right = MIN(PartialOffsets[Dim] + PartialCounts[Dim],
SelectionOffsets[Dim] + SelectionCounts[Dim]);
BlockSize *= (Right - Left);
break;
}
}
if (Dims > 0)
{
SourceBlockStride = PartialCounts[0] * OperantElementSize;
DestBlockStride = SelectionCounts[0] * OperantElementSize;
}
/* calculate first selected element and count */
BlockCount = 1;
size_t *FirstIndex = malloc(Dims * sizeof(FirstIndex[0]));
for (int Dim = 0; Dim < Dims; Dim++)
{
int Left = MAX(PartialOffsets[Dim], SelectionOffsets[Dim]);
int Right = MIN(PartialOffsets[Dim] + PartialCounts[Dim],
SelectionOffsets[Dim] + SelectionCounts[Dim]);
if (Dim > 0)
{
BlockCount *= (Right - Left);
}
FirstIndex[Dim] = Left;
}
size_t *SelectionIndex = malloc(Dims * sizeof(SelectionIndex[0]));
MapGlobalToLocalIndex(Dims, FirstIndex, SelectionOffsets, SelectionIndex);
DestBlockStartOffset = FindOffsetCM(Dims, SelectionCounts, SelectionIndex);
free(SelectionIndex);
DestBlockStartOffset *= OperantElementSize;
size_t *PartialIndex = malloc(Dims * sizeof(PartialIndex[0]));
MapGlobalToLocalIndex(Dims, FirstIndex, PartialOffsets, PartialIndex);
SourceBlockStartOffset = FindOffsetCM(Dims, PartialCounts, PartialIndex);
free(PartialIndex);
SourceBlockStartOffset *= OperantElementSize;
InData += SourceBlockStartOffset;
OutData += DestBlockStartOffset;
int i;
for (i = 0; i < BlockCount; i++)
{
memcpy(OutData, InData, BlockSize * ElementSize);
InData += SourceBlockStride;
OutData += DestBlockStride;
}
free(FirstIndex);
}
typedef struct _range_list
{
size_t start;
size_t end;
struct _range_list *next;
} * range_list;
range_list static OneDCoverage(size_t start, size_t end,
range_list uncovered_list)
{
if (uncovered_list == NULL)
return NULL;
if ((start <= uncovered_list->start) && (end >= uncovered_list->end))
{
/* this uncovered element is covered now, recurse on next */
range_list next = uncovered_list->next;
free(uncovered_list);
return OneDCoverage(start, end, next);
}
else if ((end < uncovered_list->end) && (start > uncovered_list->start))
{
/* covering a bit in the middle */
range_list new = malloc(sizeof(*new));
new->next = uncovered_list->next;
new->end = uncovered_list->end;
new->start = end + 1;
uncovered_list->end = start - 1;
uncovered_list->next = new;
return (uncovered_list);
}
else if ((end < uncovered_list->start) || (start > uncovered_list->end))
{
uncovered_list->next = OneDCoverage(start, end, uncovered_list->next);
return uncovered_list;
}
else if (start <= uncovered_list->start)
{
/* we don't cover completely nor a middle portion, so this means we span
* the beginning */
uncovered_list->start = end + 1;
uncovered_list->next = OneDCoverage(start, end, uncovered_list->next);
return uncovered_list;
}
else if (end >= uncovered_list->end)
{
/* we don't cover completely nor a middle portion, so this means we span
* the end */
uncovered_list->end = start - 1;
uncovered_list->next = OneDCoverage(start, end, uncovered_list->next);
return uncovered_list;
}
return NULL;
}
static void DumpCoverageList(range_list list)
{
if (!list)
return;
printf("%ld - %ld", list->start, list->end);
if (list->next != NULL)
{
printf(", ");
DumpCoverageList(list->next);
}
}
static void ImplementGapWarning(SstStream Stream, FFSArrayRequest Req)
{
if (Req->RequestType == Local)
{
/* no analysis here */
return;
}
if (Req->VarRec->DimCount != 1)
{
/* at this point, multidimensional fill analysis is too much */
return;
}
struct _range_list *Required = malloc(sizeof(*Required));
Required->next = NULL;
Required->start = Req->Start[0];
Required->end = Req->Start[0] + Req->Count[0] - 1;
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
size_t start = Req->VarRec->PerWriterStart[i][0];
size_t end = start + Req->VarRec->PerWriterCounts[i][0] - 1;
Required = OneDCoverage(start, end, Required);
}
if (Required != NULL)
{
printf("WARNING: Reader Rank %d requested elements %lu - %lu,\n\tbut "
"these elements were not written by any writer rank: \n",
Stream->Rank, (unsigned long)Req->Start[0],
(unsigned long)Req->Start[0] + Req->Count[0] - 1);
DumpCoverageList(Required);
}
}
static void FillReadRequests(SstStream Stream, FFSArrayRequest Reqs)
{
while (Reqs)
{
ImplementGapWarning(Stream, Reqs);
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (NeedWriter(Reqs, i))
{
/* if needed this writer fill destination with acquired data */
int ElementSize = Reqs->VarRec->ElementSize;
int DimCount = Reqs->VarRec->DimCount;
size_t *GlobalDimensions = Reqs->VarRec->GlobalDims;
size_t *GlobalDimensionsFree = NULL;
size_t *RankOffset = Reqs->VarRec->PerWriterStart[i];
size_t *RankOffsetFree = NULL;
size_t *RankSize = Reqs->VarRec->PerWriterCounts[i];
size_t *SelOffset = Reqs->Start;
size_t *SelOffsetFree = NULL;
size_t *SelSize = Reqs->Count;
char *Type = Reqs->VarRec->Type;
void *IncomingData = Reqs->VarRec->PerWriterIncomingData[i];
int FreeIncoming = 0;
if (Reqs->RequestType == Local)
{
RankOffset = calloc(DimCount, sizeof(RankOffset[0]));
RankOffsetFree = RankOffset;
GlobalDimensions =
calloc(DimCount, sizeof(GlobalDimensions[0]));
GlobalDimensionsFree = GlobalDimensions;
if (SelOffset == NULL)
{
SelOffset = calloc(DimCount, sizeof(RankOffset[0]));
SelOffsetFree = SelOffset;
}
for (int i = 0; i < DimCount; i++)
{
GlobalDimensions[i] = RankSize[i];
}
}
if ((Stream->WriterConfigParams->CompressionMethod ==
SstCompressZFP) &&
ZFPcompressionPossible(Type, DimCount))
{
#ifdef ADIOS2_HAVE_ZFP
/*
* replace old IncomingData with uncompressed, and free
* afterwards
*/
size_t IncomingSize =
Reqs->VarRec->PerWriterIncomingSize[i];
FreeIncoming = 1;
IncomingData =
FFS_ZFPDecompress(Stream, DimCount, Type, IncomingData,
IncomingSize, RankSize, NULL);
#endif
}
if (Stream->ConfigParams->IsRowMajor)
{
ExtractSelectionFromPartialRM(
ElementSize, DimCount, GlobalDimensions, RankOffset,
RankSize, SelOffset, SelSize, IncomingData, Reqs->Data);
}
else
{
ExtractSelectionFromPartialCM(
ElementSize, DimCount, GlobalDimensions, RankOffset,
RankSize, SelOffset, SelSize, IncomingData, Reqs->Data);
}
free(SelOffsetFree);
free(GlobalDimensionsFree);
free(RankOffsetFree);
if (FreeIncoming)
{
/* free uncompressed */
free(IncomingData);
}
}
}
Reqs = Reqs->Next;
}
}
extern SstStatusValue SstFFSPerformGets(SstStream Stream)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
SstStatusValue Ret;
IssueReadRequests(Stream, Info->PendingVarRequests);
Ret = WaitForReadRequests(Stream);
if (Ret == SstSuccess)
{
FillReadRequests(Stream, Info->PendingVarRequests);
}
else
{
CP_verbose(Stream, "Some memory read failed, not filling requests and "
"returning failure\n");
}
ClearReadRequests(Stream);
return Ret;
}
extern void SstFFSWriterEndStep(SstStream Stream, size_t Timestep)
{
struct FFSWriterMarshalBase *Info;
struct FFSFormatBlock *Formats = NULL;
FMFormat AttributeFormat = NULL;
TAU_START("Marshaling overhead in SstFFSWriterEndStep");
CP_verbose(Stream, "Calling SstWriterEndStep\n");
// if field lists have changed, register formats with FFS local context, add
// to format chain
if (!Stream->WriterMarshalData)
{
InitMarshalData(Stream);
}
Info = (struct FFSWriterMarshalBase *)Stream->WriterMarshalData;
if (!Info->MetaFormat && Info->MetaFieldCount)
{
struct FFSFormatBlock *Block = malloc(sizeof(*Block));
FMStructDescRec struct_list[4] = {
{NULL, NULL, 0, NULL},
{"complex4", fcomplex_field_list, sizeof(fcomplex_struct), NULL},
{"complex8", dcomplex_field_list, sizeof(dcomplex_struct), NULL},
{NULL, NULL, 0, NULL}};
struct_list[0].format_name = "MetaData";
struct_list[0].field_list = Info->MetaFields;
struct_list[0].struct_size =
FMstruct_size_field_list(Info->MetaFields, sizeof(char *));
FMFormat Format =
register_data_format(Info->LocalFMContext, &struct_list[0]);
Info->MetaFormat = Format;
Block->FormatServerRep =
get_server_rep_FMformat(Format, &Block->FormatServerRepLen);
Block->FormatIDRep =
get_server_ID_FMformat(Format, &Block->FormatIDRepLen);
Block->Next = NULL;
Formats = Block;
}
if (!Info->DataFormat && Info->DataFieldCount)
{
struct FFSFormatBlock *Block = malloc(sizeof(*Block));
FMStructDescRec struct_list[4] = {
{NULL, NULL, 0, NULL},
{"complex4", fcomplex_field_list, sizeof(fcomplex_struct), NULL},
{"complex8", dcomplex_field_list, sizeof(dcomplex_struct), NULL},
{NULL, NULL, 0, NULL}};
struct_list[0].format_name = "Data";
struct_list[0].field_list = Info->DataFields;
struct_list[0].struct_size =
FMstruct_size_field_list(Info->DataFields, sizeof(char *));
FMFormat Format =
register_data_format(Info->LocalFMContext, &struct_list[0]);
Info->DataFormat = Format;
Block->FormatServerRep =
get_server_rep_FMformat(Format, &Block->FormatServerRepLen);
Block->FormatIDRep =
get_server_ID_FMformat(Format, &Block->FormatIDRepLen);
Block->Next = NULL;
if (Formats)
{
Block->Next = Formats;
Formats = Block;
}
else
{
Formats = Block;
}
}
if (Info->AttributeFields)
{
struct FFSFormatBlock *Block = calloc(1, sizeof(*Block));
FMFormat Format = FMregister_simple_format(
Info->LocalFMContext, "Attributes", Info->AttributeFields,
FMstruct_size_field_list(Info->AttributeFields, sizeof(char *)));
AttributeFormat = Format;
Block->FormatServerRep =
get_server_rep_FMformat(Format, &Block->FormatServerRepLen);
Block->FormatIDRep =
get_server_ID_FMformat(Format, &Block->FormatIDRepLen);
Block->Next = NULL;
if (Formats)
{
Block->Next = Formats;
Formats = Block;
}
else
{
Formats = Block;
}
}
// Encode Metadata and Data to create contiguous data blocks
FFSTimestepInfo TSInfo = malloc(sizeof(*TSInfo));
FFSBuffer MetaEncodeBuffer = create_FFSBuffer();
FFSBuffer DataEncodeBuffer = create_FFSBuffer();
FFSBuffer AttributeEncodeBuffer = NULL;
struct _SstData DataRec;
struct _SstData MetaDataRec;
struct _SstData AttributeRec;
int MetaDataSize;
int DataSize;
int AttributeSize = 0;
struct FFSMetadataInfoStruct *MBase;
if (Info->DataFormat)
{
DataRec.block =
FFSencode(DataEncodeBuffer, Info->DataFormat, Stream->D, &DataSize);
DataRec.DataSize = DataSize;
}
else
{
DataRec.block = NULL;
DataRec.DataSize = 0;
DataSize = 0;
}
TSInfo->DataEncodeBuffer = DataEncodeBuffer;
MBase = Stream->M;
MBase->DataBlockSize = DataSize;
MetaDataRec.block =
FFSencode(MetaEncodeBuffer, Info->MetaFormat, Stream->M, &MetaDataSize);
MetaDataRec.DataSize = MetaDataSize;
TSInfo->MetaEncodeBuffer = MetaEncodeBuffer;
if (Info->AttributeFields)
{
AttributeEncodeBuffer = create_FFSBuffer();
AttributeRec.block = FFSencode(AttributeEncodeBuffer, AttributeFormat,
Info->AttributeData, &AttributeSize);
AttributeRec.DataSize = AttributeSize;
}
else
{
AttributeRec.block = NULL;
AttributeRec.DataSize = 0;
}
/* free all those copied dimensions, etc */
MBase = Stream->M;
size_t *tmp = MBase->BitField;
/*
* BitField value is saved away from FMfree_var_rec_elements() so that it
* isn't unnecessarily free'd.
*/
MBase->BitField = NULL;
if (Info->MetaFormat)
FMfree_var_rec_elements(Info->MetaFormat, Stream->M);
if (Info->DataFormat)
FMfree_var_rec_elements(Info->DataFormat, Stream->D);
if (Stream->M && Stream->MetadataSize)
memset(Stream->M, 0, Stream->MetadataSize);
if (Stream->D && Stream->DataSize)
memset(Stream->D, 0, Stream->DataSize);
MBase->BitField = tmp;
// Call SstInternalProvideStep with Metadata block, Data block and (any new)
// formatID and formatBody
// printf("MetaDatablock is (Length %d):\n", MetaDataSize);
// FMdump_encoded_data(Info->MetaFormat, MetaDataRec.block, 1024000);
// printf("\nDatablock is :\n");
// FMdump_encoded_data(Info->DataFormat, DataRec.block, 1024000);
// if (AttributeEncodeBuffer) {
// printf("\nAttributeBlock is :\n");
// FMdump_encoded_data(AttributeFormat, AttributeRec.block, 1024000);
// }
TAU_STOP("Marshaling overhead in SstFFSWriterEndStep");
SstInternalProvideTimestep(Stream, &MetaDataRec, &DataRec, Timestep,
Formats, FreeTSInfo, TSInfo, &AttributeRec,
FreeAttrInfo, AttributeEncodeBuffer);
if (AttributeEncodeBuffer)
{
free_FFSBuffer(AttributeEncodeBuffer);
}
while (Formats)
{
struct FFSFormatBlock *Tmp = Formats->Next;
free(Formats);
Formats = Tmp;
}
if (Info->AttributeFields)
free_FMfield_list(Info->AttributeFields);
Info->AttributeFields = NULL;
Info->AttributeFieldCount = 0;
if (Info->AttributeData)
free(Info->AttributeData);
Info->AttributeData = NULL;
Info->AttributeSize = 0;
}
static void LoadAttributes(SstStream Stream, TSMetadataMsg MetaData)
{
static int DumpMetadata = -1;
Stream->AttrSetupUpcall(Stream->SetupUpcallReader, NULL, NULL, NULL);
for (int WriterRank = 0; WriterRank < Stream->WriterCohortSize;
WriterRank++)
{
FMFieldList FieldList;
FMStructDescList FormatList;
void *BaseData;
FFSTypeHandle FFSformat;
if (MetaData->AttributeData[WriterRank].DataSize == 0)
return;
FFSformat = FFSTypeHandle_from_encode(
Stream->ReaderFFSContext,
MetaData->AttributeData[WriterRank].block);
if (!FFShas_conversion(FFSformat))
{
FMContext FMC = FMContext_from_FFS(Stream->ReaderFFSContext);
FMFormat Format = FMformat_from_ID(
FMC, MetaData->AttributeData[WriterRank].block);
FMStructDescList List =
FMcopy_struct_list(format_list_of_FMFormat(Format));
FMlocalize_structs(List);
establish_conversion(Stream->ReaderFFSContext, FFSformat, List);
FMfree_struct_list(List);
}
if (FFSdecode_in_place_possible(FFSformat))
{
FFSdecode_in_place(Stream->ReaderFFSContext,
MetaData->AttributeData[WriterRank].block,
&BaseData);
}
else
{
int DecodedLength = FFS_est_decode_length(
Stream->ReaderFFSContext,
MetaData->AttributeData[WriterRank].block,
MetaData->AttributeData[WriterRank].DataSize);
BaseData = malloc(DecodedLength);
FFSBuffer decode_buf =
create_fixed_FFSBuffer(BaseData, DecodedLength);
FFSdecode_to_buffer(Stream->ReaderFFSContext,
MetaData->AttributeData[WriterRank].block,
decode_buf);
}
if (DumpMetadata == -1)
{
DumpMetadata = (getenv("SstDumpMetadata") != NULL);
}
if (DumpMetadata && (Stream->Rank == 0))
{
printf("\nIncomingAttributeDatablock from WriterRank %d is %p :\n",
WriterRank, BaseData);
FMdump_data(FMFormat_of_original(FFSformat), BaseData, 1024000);
printf("\n\n");
}
FormatList = format_list_of_FMFormat(FMFormat_of_original(FFSformat));
FieldList = FormatList[0].field_list;
int i = 0;
while (FieldList[i].field_name)
{
char *FieldName;
void *field_data = (char *)BaseData + FieldList[i].field_offset;
char *Type;
int ElemSize;
BreakdownVarName(FieldList[i].field_name, &FieldName, &Type,
&ElemSize);
Stream->AttrSetupUpcall(Stream->SetupUpcallReader, FieldName, Type,
field_data);
free(Type);
free(FieldName);
i++;
}
}
}
static void LoadFormats(SstStream Stream, FFSFormatList Formats)
{
FFSFormatList Entry = Formats;
while (Entry)
{
char *FormatID = malloc(Entry->FormatIDRepLen);
char *FormatServerRep = malloc(Entry->FormatServerRepLen);
memcpy(FormatID, Entry->FormatIDRep, Entry->FormatIDRepLen);
memcpy(FormatServerRep, Entry->FormatServerRep,
Entry->FormatServerRepLen);
load_external_format_FMcontext(
FMContext_from_FFS(Stream->ReaderFFSContext), FormatID,
Entry->FormatIDRepLen, FormatServerRep);
free(FormatID);
Entry = Entry->Next;
}
}
static int NameIndicatesArray(const char *Name)
{
int Len = strlen(Name);
return (strcmp("Dims", Name + Len - 4) == 0);
}
extern void FFSClearTimestepData(SstStream Stream)
{
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
if (Info->WriterInfo[i].RawBuffer)
free(Info->WriterInfo[i].RawBuffer);
}
memset(Info->WriterInfo, 0,
sizeof(Info->WriterInfo[0]) * Stream->WriterCohortSize);
memset(Info->MetadataBaseAddrs, 0,
sizeof(Info->MetadataBaseAddrs[0]) * Stream->WriterCohortSize);
memset(Info->MetadataFieldLists, 0,
sizeof(Info->MetadataFieldLists[0]) * Stream->WriterCohortSize);
memset(Info->DataBaseAddrs, 0,
sizeof(Info->DataBaseAddrs[0]) * Stream->WriterCohortSize);
memset(Info->DataFieldLists, 0,
sizeof(Info->DataFieldLists[0]) * Stream->WriterCohortSize);
for (int i = 0; i < Info->VarCount; i++)
{
free(Info->VarList[i].VarName);
free(Info->VarList[i].PerWriterMetaFieldDesc);
free(Info->VarList[i].PerWriterDataFieldDesc);
free(Info->VarList[i].PerWriterStart);
free(Info->VarList[i].PerWriterCounts);
free(Info->VarList[i].PerWriterIncomingData);
free(Info->VarList[i].PerWriterIncomingSize);
if (Info->VarList[i].Type)
free(Info->VarList[i].Type);
}
Info->VarCount = 0;
}
static void BuildVarList(SstStream Stream, TSMetadataMsg MetaData,
int WriterRank)
{
FFSTypeHandle FFSformat;
FMFieldList FieldList;
FMStructDescList FormatList;
void *BaseData;
static int DumpMetadata = -1;
/* incoming metadata is all of our information about what was written
* and is available to be read. We'll process the data from each node
* separately, but in such a way that we don't need to process the
* MetaData again. That means keeping around the information that we'll
* need to respond to Get[Sync,Deferred] actions later. For this we use
* the VarList, which is keyed by the address of the Variable object
* created at the ADIOS2 level. So, we run through the individual
* metadata blocks from a rank. For each field set (one field for
* atomic values, 4 for arrays), we look to see if we that name already
* exists in the VarList (never for WriterRank==0), and if not we create
* it and do the upcall to create the Variable object. Then for each
* Variable, we note global geometry, and for each rank we note the
* FMField descriptor for its entry in the MetaData block and the
* geometry for that block (Start + Offset arrays). Also for each rank
* we track the info that we'll need later (base address of decoded
* metadata), format lists /buffers that might need freeing, etc.
*/
struct FFSReaderMarshalBase *Info = Stream->ReaderMarshalData;
if (!Info)
{
Info = malloc(sizeof(*Info));
memset(Info, 0, sizeof(*Info));
Stream->ReaderMarshalData = Info;
Info->WriterInfo =
calloc(sizeof(Info->WriterInfo[0]), Stream->WriterCohortSize);
Info->MetadataBaseAddrs = calloc(sizeof(Info->MetadataBaseAddrs[0]),
Stream->WriterCohortSize);
Info->MetadataFieldLists = calloc(sizeof(Info->MetadataFieldLists[0]),
Stream->WriterCohortSize);
Info->DataBaseAddrs =
calloc(sizeof(Info->DataBaseAddrs[0]), Stream->WriterCohortSize);
Info->DataFieldLists =
calloc(sizeof(Info->DataFieldLists[0]), Stream->WriterCohortSize);
}
if (!MetaData->Metadata[WriterRank].block)
{
fprintf(stderr,
"FAILURE! MetaData->Metadata[WriterRank]->block == "
"NULL for WriterRank = %d\n",
WriterRank);
}
FFSformat = FFSTypeHandle_from_encode(Stream->ReaderFFSContext,
MetaData->Metadata[WriterRank].block);
if (!FFShas_conversion(FFSformat))
{
FMContext FMC = FMContext_from_FFS(Stream->ReaderFFSContext);
FMFormat Format =
FMformat_from_ID(FMC, MetaData->Metadata[WriterRank].block);
FMStructDescList List =
FMcopy_struct_list(format_list_of_FMFormat(Format));
FMlocalize_structs(List);
establish_conversion(Stream->ReaderFFSContext, FFSformat, List);
FMfree_struct_list(List);
}
if (FFSdecode_in_place_possible(FFSformat))
{
FFSdecode_in_place(Stream->ReaderFFSContext,
MetaData->Metadata[WriterRank].block, &BaseData);
}
else
{
int DecodedLength = FFS_est_decode_length(
Stream->ReaderFFSContext, MetaData->Metadata[WriterRank].block,
MetaData->Metadata[WriterRank].DataSize);
BaseData = malloc(DecodedLength);
FFSBuffer decode_buf = create_fixed_FFSBuffer(BaseData, DecodedLength);
FFSdecode_to_buffer(Stream->ReaderFFSContext,
MetaData->Metadata[WriterRank].block, decode_buf);
}
if (DumpMetadata == -1)
{
DumpMetadata = (getenv("SstDumpMetadata") != NULL);
}
if (DumpMetadata && (Stream->Rank == 0))
{
printf("\nIncomingMetadatablock from WriterRank %d is %p :\n",
WriterRank, BaseData);
FMdump_data(FMFormat_of_original(FFSformat), BaseData, 1024000);
printf("\n\n");
}
Info->MetadataBaseAddrs[WriterRank] = BaseData;
FormatList = format_list_of_FMFormat(FMFormat_of_original(FFSformat));
FieldList = FormatList[0].field_list;
while (strncmp(FieldList->field_name, "BitField", 8) == 0)
FieldList++;
while (FieldList->field_name &&
(strncmp(FieldList->field_name, "DataBlockSize", 8) == 0))
FieldList++;
int i = 0;
int j = 0;
while (FieldList[i].field_name)
{
void *field_data = (char *)BaseData + FieldList[i].field_offset;
if (NameIndicatesArray(FieldList[i].field_name))
{
MetaArrayRec *meta_base = field_data;
char *ArrayName;
char *Type;
FFSVarRec VarRec = NULL;
int ElementSize;
if (!FFSBitfieldTest(BaseData, j))
{
/* only work with fields that were written */
i += 4;
j++;
continue;
}
BreakdownArrayName(FieldList[i].field_name, &ArrayName, &Type,
&ElementSize);
if (WriterRank != 0)
{
VarRec = LookupVarByName(Stream, ArrayName);
}
if ((meta_base->Dims > 1) &&
(Stream->WriterConfigParams->IsRowMajor !=
Stream->ConfigParams->IsRowMajor))
{
/* if we're getting data from someone of the other array gender,
* switcheroo */
ReverseDimensions(meta_base->Shape, meta_base->Dims);
ReverseDimensions(meta_base->Count, meta_base->Dims);
ReverseDimensions(meta_base->Offsets, meta_base->Dims);
}
if (!VarRec)
{
VarRec = CreateVarRec(Stream, ArrayName);
VarRec->DimCount = meta_base->Dims;
VarRec->Type = Type;
VarRec->ElementSize = ElementSize;
VarRec->Variable = Stream->ArraySetupUpcall(
Stream->SetupUpcallReader, ArrayName, Type, meta_base->Dims,
meta_base->Shape, meta_base->Offsets, meta_base->Count);
}
if (WriterRank == 0)
{
VarRec->GlobalDims = meta_base->Shape;
}
VarRec->PerWriterStart[WriterRank] = meta_base->Offsets;
VarRec->PerWriterCounts[WriterRank] = meta_base->Count;
VarRec->PerWriterMetaFieldDesc[WriterRank] = &FieldList[i];
VarRec->PerWriterDataFieldDesc[WriterRank] = NULL;
Stream->ArrayBlocksInfoUpcall(Stream->SetupUpcallReader,
VarRec->Variable, Type, WriterRank,
meta_base->Dims, meta_base->Shape,
meta_base->Offsets, meta_base->Count);
i += 4;
free(ArrayName);
}
else
{
/* simple field */
char *FieldName = strdup(FieldList[i].field_name + 4); // skip SST_
FFSVarRec VarRec = NULL;
if (!FFSBitfieldTest(BaseData, j))
{
/* only work with fields that were written */
i++;
j++;
continue;
}
if (WriterRank != 0)
{
VarRec = LookupVarByName(Stream, FieldName);
}
if (!VarRec)
{
char *Type = TranslateFFSType2ADIOS(FieldList[i].field_type,
FieldList[i].field_size);
VarRec = CreateVarRec(Stream, FieldName);
VarRec->DimCount = 0;
VarRec->Variable = Stream->VarSetupUpcall(
Stream->SetupUpcallReader, FieldName, Type, field_data);
free(Type);
}
VarRec->PerWriterMetaFieldDesc[WriterRank] = &FieldList[i];
VarRec->PerWriterDataFieldDesc[WriterRank] = NULL;
free(FieldName);
i++;
}
/* real variable count is in j, i tracks the entries in the metadata */
j++;
}
}
extern void FFSMarshalInstallPreciousMetadata(SstStream Stream,
TSMetadataMsg MetaData)
{
if (!Stream->ReaderFFSContext)
{
FMContext Tmp = create_local_FMcontext();
Stream->ReaderFFSContext = create_FFSContext_FM(Tmp);
free_FMcontext(Tmp);
}
LoadFormats(Stream, MetaData->Formats);
LoadAttributes(Stream, MetaData);
}
extern void FFSMarshalInstallMetadata(SstStream Stream, TSMetadataMsg MetaData)
{
FFSMarshalInstallPreciousMetadata(Stream, MetaData);
for (int i = 0; i < Stream->WriterCohortSize; i++)
{
BuildVarList(Stream, MetaData, i);
}
}
static void FFSBitfieldSet(struct FFSMetadataInfoStruct *MBase, int Bit)
{
int Element = Bit / 64;
int ElementBit = Bit % 64;
if (Element >= MBase->BitFieldCount)
{
MBase->BitField =
realloc(MBase->BitField, sizeof(size_t) * (Element + 1));
memset(MBase->BitField + MBase->BitFieldCount * sizeof(size_t), 0,
(Element - MBase->BitFieldCount + 1) * sizeof(size_t));
MBase->BitFieldCount = Element + 1;
}
MBase->BitField[Element] |= (1 << ElementBit);
}
static int FFSBitfieldTest(struct FFSMetadataInfoStruct *MBase, int Bit)
{
int Element = Bit / 64;
int ElementBit = Bit % 64;
if (Element >= MBase->BitFieldCount)
{
MBase->BitField =
realloc(MBase->BitField, sizeof(size_t) * (Element + 1));
memset(MBase->BitField + MBase->BitFieldCount * sizeof(size_t), 0,
(Element - MBase->BitFieldCount + 1) * sizeof(size_t));
MBase->BitFieldCount = Element + 1;
}
return ((MBase->BitField[Element] & (1 << ElementBit)) ==
(1 << ElementBit));
}
extern void SstFFSSetZFPParams(SstStream Stream, attr_list Attrs)
{
if (Stream->WriterMarshalData)
{
struct FFSWriterMarshalBase *Info = Stream->WriterMarshalData;
if (Info->ZFPParams)
free_attr_list(Info->ZFPParams);
add_ref_attr_list(Attrs);
Info->ZFPParams = Attrs;
}
}
extern void SstFFSMarshal(SstStream Stream, void *Variable, const char *Name,
const char *Type, size_t ElemSize, size_t DimCount,
const size_t *Shape, const size_t *Count,
const size_t *Offsets, const void *Data)
{
struct FFSMetadataInfoStruct *MBase;
FFSWriterRec Rec = LookupWriterRec(Stream, Variable);
if (!Rec)
{
Rec = CreateWriterRec(Stream, Variable, Name, Type, ElemSize, DimCount);
}
MBase = Stream->M;
FFSBitfieldSet(MBase, Rec->FieldID);
if (Rec->DimCount == 0)
{
char *base = Stream->M + Rec->MetaOffset;
memcpy(base, Data, ElemSize);
}
else
{
MetaArrayRec *MetaEntry = Stream->M + Rec->MetaOffset;
ArrayRec *DataEntry = Stream->D + Rec->DataOffset;
/* handle metadata */
MetaEntry->Dims = DimCount;
if (Shape)
MetaEntry->Shape = CopyDims(DimCount, Shape);
else
MetaEntry->Shape = NULL;
MetaEntry->Count = CopyDims(DimCount, Count);
if (Offsets)
MetaEntry->Offsets = CopyDims(DimCount, Offsets);
else
MetaEntry->Offsets = NULL;
if ((Stream->ConfigParams->CompressionMethod == SstCompressZFP) &&
ZFPcompressionPossible(Type, DimCount))
{
#ifdef ADIOS2_HAVE_ZFP
/* this should never be true if ZFP is not available */
size_t ByteCount;
char *Output = FFS_ZFPCompress(Stream, Rec->DimCount, Rec->Type,
(void *)Data, Count, &ByteCount);
DataEntry->ElemCount = ByteCount;
DataEntry->Array = Output;
#endif
}
else
{
/* normal array case */
size_t ElemCount = CalcSize(DimCount, Count);
DataEntry->ElemCount = ElemCount;
/* this is PutSync case, so we have to copy the data NOW */
DataEntry->Array = malloc(ElemCount * ElemSize);
memcpy(DataEntry->Array, Data, ElemCount * ElemSize);
}
}
}
extern void SstFFSMarshalAttribute(SstStream Stream, const char *Name,
const char *Type, size_t ElemSize,
size_t ElemCount, const void *Data)
{
struct FFSWriterMarshalBase *Info;
Info = (struct FFSWriterMarshalBase *)Stream->WriterMarshalData;
const char *String = NULL;
const char *DataAddress = Data;
if (strcmp(Type, "string") == 0)
{
ElemSize = sizeof(char *);
String = Data;
DataAddress = (const char *)&String;
}
if (ElemCount == -1)
{
// simple field, only simple attribute name and value
char *SstName = BuildVarName(Name, Type, ElemSize);
AddField(&Info->AttributeFields, &Info->AttributeFieldCount, SstName,
Type, ElemSize);
free(SstName);
RecalcAttributeStorageSize(Stream);
int DataOffset =
Info->AttributeFields[Info->AttributeFieldCount - 1].field_offset;
memcpy(Info->AttributeData + DataOffset, DataAddress, ElemSize);
}
else
{
/* // Array field. To Metadata, add FMFields for DimCount, Shape, Count
*/
/* // and Offsets matching _MetaArrayRec */
/* char *ArrayName = BuildStaticArrayName(Name, Type, ElemCount); */
/* AddField(&Info->AttributeFields, &Info->AttributeFieldCount,
* ArrayName, Type, */
/* sizeof(size_t)); */
/* free(ArrayName); */
/* Rec->MetaOffset = */
/* Info->MetaFields[Info->MetaFieldCount - 1].field_offset; */
/* char *ShapeName = ConcatName(Name, "Shape"); */
/* char *CountName = ConcatName(Name, "Count"); */
/* char *OffsetsName = ConcatName(Name, "Offsets"); */
/* AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount,
* ShapeName, */
/* "integer", sizeof(size_t), DimCount); */
/* AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount,
* CountName, */
/* "integer", sizeof(size_t), DimCount); */
/* AddFixedArrayField(&Info->MetaFields, &Info->MetaFieldCount, */
/* OffsetsName, "integer", sizeof(size_t), DimCount);
*/
/* free(ShapeName); */
/* free(CountName); */
/* free(OffsetsName); */
/* RecalcMarshalStorageSize(Stream); */
/* if ((Stream->ConfigParams->CompressionMethod == SstCompressZFP) && */
/* ZFPcompressionPossible(Type, DimCount)) */
/* { */
/* Type = "char"; */
/* ElemSize = 1; */
/* } */
/* // To Data, add FMFields for ElemCount and Array matching _ArrayRec
*/
/* char *ElemCountName = ConcatName(Name, "ElemCount"); */
/* AddField(&Info->DataFields, &Info->DataFieldCount, ElemCountName, */
/* "integer", sizeof(size_t)); */
/* Rec->DataOffset = */
/* Info->DataFields[Info->DataFieldCount - 1].field_offset; */
/* char *SstName = ConcatName(Name, ""); */
/* AddVarArrayField(&Info->DataFields, &Info->DataFieldCount, SstName,
*/
/* Type, ElemSize, ElemCountName); */
/* free(SstName); */
/* free(ElemCountName); */
/* RecalcMarshalStorageSize(Stream); */
/* // Changing the formats renders these invalid */
/* Info->MetaFormat = NULL; */
/* Info->DataFormat = NULL; */
}
}
| 34.304839 | 80 | 0.586476 | [
"geometry",
"object",
"shape"
] |
bd89a4105c030b966b942f72a7a1a901d1465e5a | 1,957 | h | C | source/GbmTree.h | Jde-cpp/LightGbm | 648542c66c12b585d5e392363a390a06891d7b18 | [
"MIT"
] | null | null | null | source/GbmTree.h | Jde-cpp/LightGbm | 648542c66c12b585d5e392363a390a06891d7b18 | [
"MIT"
] | null | null | null | source/GbmTree.h | Jde-cpp/LightGbm | 648542c66c12b585d5e392363a390a06891d7b18 | [
"MIT"
] | null | null | null | #pragma once
#include "Booster.h"
namespace Jde::AI::Dts::LightGbm
{
/* struct ITree
{
template<class TTree>
static ITree& GetInstance()noexcept;
virtual double Predict( const double* pFeatures )noexcept=0;
virtual const string_view* FeatureNames()const noexcept=0;
virtual size_t FeatureCount()const noexcept=0;
virtual MapPtr<string,double> FeatureImportances( bool splitImportance )const=0;
};
*/
/*
struct Tree : public ITree
{
Tree( const fs::path& path )noexcept(false);
double Predict( const double* pFeatures )noexcept override{ return _booster.Predict(pFeatures); }
const string_view* FeatureNames()const noexcept override{ return _features.data(); }
size_t FeatureCount()const noexcept override{ return _features.size(); }
map<string,int> FeatureImportance();
MapPtr<string,double> FeatureImportances( bool splitImportance )const noexcept(false) override{ return _booster.FeatureImportances(splitImportance); }
private:
Booster _booster;
vector<string_view> _features;
};
*/
/* template<size_t TFeatureCount>
struct TreeBase : public ITree
{
constexpr TreeBase( const std::array<string_view,TFeatureCount>& featureCount );
const std::array<string_view,TFeatureCount> Features;
const string_view* FeatureNames()const noexcept override{ return Features.data(); }
size_t FeatureCount()const noexcept{return FeatureCnt;}
constexpr static size_t FeatureCnt{TFeatureCount};
};
template<size_t TFeatureCount>
constexpr TreeBase<TFeatureCount>::TreeBase( const std::array<string_view,TFeatureCount>& features ):
Features{features}
{}
template<class TTree>
ITree& ITree::GetInstance()noexcept
{
if( TTree::_pInstance==nullptr )
TTree::_pInstance = std::unique_ptr<TTree>( new TTree() );
return *TTree::_pInstance;
}
*/
//JDE_GBM_VISIBILITY sp<ITree> GetPrediction( const fs::path& path, uint16 minuteStart, bool isLong );
//JDE_GBM_VISIBILITY void ClearTrees( uint16 minuteStart );
}
| 34.946429 | 152 | 0.759325 | [
"vector"
] |
bd8c5a600c594493bc31f850100d2b20e9cc4c43 | 3,654 | h | C | src/audio/aubio/src/fvec.h | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | 22 | 2017-11-11T10:29:37.000Z | 2021-10-16T16:42:39.000Z | src/audio/aubio/src/fvec.h | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | 26 | 2017-11-11T08:52:59.000Z | 2018-01-18T11:34:12.000Z | src/audio/aubio/src/fvec.h | vrushank-agrawal/video_editor_BX23 | 3a458114f499e0ba3d1c61afde2b9d30bc76459b | [
"Apache-2.0"
] | 4 | 2019-05-14T16:18:32.000Z | 2021-08-06T01:55:52.000Z | /*
Copyright (C) 2003-2015 Paul Brossier <piem@aubio.org>
This file is part of aubio.
aubio is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
aubio is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with aubio. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AUBIO_FVEC_H
#define AUBIO_FVEC_H
#ifdef __cplusplus
extern "C" {
#endif
/** \file
Vector of real-valued data
This file specifies the ::fvec_t buffer type, which is used throughout aubio
to store vector of real-valued ::smpl_t.
\example test-fvec.c
*/
/** Buffer for real data
Vector of real-valued data
::fvec_t is is the structure used to store vector of real-valued data, ::smpl_t .
\code
uint_t buffer_size = 1024;
// create a vector of 512 values
fvec_t * input = new_fvec (buffer_size);
// set some values of the vector
input->data[23] = 2.;
// ..
// compute the mean of the vector
mean = fvec_mean(a_vector);
// destroy the vector
del_fvec(a_vector);
\endcode
See `examples/` and `tests/src` directories for more examples.
*/
typedef struct {
uint_t length; /**< length of buffer */
smpl_t *data; /**< data vector of length ::fvec_t.length */
} fvec_t;
/** fvec_t buffer creation function
\param length the length of the buffer to create
*/
fvec_t * new_fvec(uint_t length);
/** fvec_t buffer deletion function
\param s buffer to delete as returned by new_fvec()
*/
void del_fvec(fvec_t *s);
/** read sample value in a buffer
\param s vector to read from
\param position sample position to read from
*/
smpl_t fvec_get_sample(const fvec_t *s, uint_t position);
/** write sample value in a buffer
\param s vector to write to
\param data value to write in s->data[position]
\param position sample position to write to
*/
void fvec_set_sample(fvec_t *s, smpl_t data, uint_t position);
/** read data from a buffer
\param s vector to read from
*/
smpl_t * fvec_get_data(const fvec_t *s);
/** print out fvec data
\param s vector to print out
*/
void fvec_print(const fvec_t *s);
/** set all elements to a given value
\param s vector to modify
\param val value to set elements to
*/
void fvec_set_all (fvec_t *s, smpl_t val);
/** set all elements to zero
\param s vector to modify
*/
void fvec_zeros(fvec_t *s);
/** set all elements to ones
\param s vector to modify
*/
void fvec_ones(fvec_t *s);
/** revert order of vector elements
\param s vector to revert
*/
void fvec_rev(fvec_t *s);
/** apply weight to vector
If the weight vector is longer than s, only the first elements are used. If
the weight vector is shorter than s, the last elements of s are not weighted.
\param s vector to weight
\param weight weighting coefficients
*/
void fvec_weight(fvec_t *s, const fvec_t *weight);
/** make a copy of a vector
\param s source vector
\param t vector to copy to
*/
void fvec_copy(const fvec_t *s, fvec_t *t);
/** make a copy of a vector, applying weights to each element
\param in input vector
\param weight weights vector
\param out output vector
*/
void fvec_weighted_copy(const fvec_t *in, const fvec_t *weight, fvec_t *out);
#ifdef __cplusplus
}
#endif
#endif /* AUBIO_FVEC_H */
| 20.413408 | 83 | 0.710454 | [
"vector"
] |
bd8dca948237a05883cdb1bcc467b849f33afa9e | 1,620 | h | C | Cpp-C/Eta/Impl/Converter/Include/rtr/EnumTableDefinition.h | krico/Real-Time-SDK | 534534199f1595f0dea121f02a57db4b2c0aeae2 | [
"Apache-2.0"
] | 107 | 2015-07-27T23:43:04.000Z | 2019-01-03T07:11:27.000Z | Cpp-C/Eta/Impl/Converter/Include/rtr/EnumTableDefinition.h | krico/Real-Time-SDK | 534534199f1595f0dea121f02a57db4b2c0aeae2 | [
"Apache-2.0"
] | 91 | 2015-07-28T15:40:43.000Z | 2018-12-31T09:37:19.000Z | Cpp-C/Eta/Impl/Converter/Include/rtr/EnumTableDefinition.h | krico/Real-Time-SDK | 534534199f1595f0dea121f02a57db4b2c0aeae2 | [
"Apache-2.0"
] | 68 | 2015-07-27T08:35:47.000Z | 2019-01-01T07:59:39.000Z | /*|-----------------------------------------------------------------------------
*| This source code is provided under the Apache 2.0 license --
*| and is provided AS IS with no warranty or guarantee of fit for purpose. --
*| See the project's LICENSE.md for details. --
*| Copyright (C) 2020 Refinitiv. All rights reserved. --
*|-----------------------------------------------------------------------------
*/
#ifndef __rtr_enumTableDefinition
#define __rtr_enumTableDefinition
#include "rtr/rsslHashTable.h"
#include "rtr/jsonToRwfSimple.h"
/* This type contains Enum table definition to map Display value(utf8) to a enum value.*/
typedef struct {
RsslHashLink displayValueLink;
RsslUInt16 enumValue;
RsslBuffer enumDisplay; /* This is in the utf8 format */
}EnumDefinition;
class EnumTableDefinition
{
public:
EnumTableDefinition(jsonToRwfSimple* jonToRwfSimple, RsslUInt16 maxCount);
void decreaseRefCount(); /* This is used to decrease reference count to delete this object */
RsslRet addEnumDefinition(RsslEnumTypeTable* pEnumTypeTable, RsslBuffer* displayValue, RsslUInt32 hashSum, int* foundEnumValue);
RsslBool findEnumDefinition(RsslBuffer* displayValue, RsslUInt32 hashSum, int* foundEnumValue);
private:
RsslHashTable _enumByDispalyValue;
RsslInt32 _referenceCount;
jsonToRwfSimple* _pJsonToRwfSimple;
bool _initializedHashTable;
RsslUInt16 _maxCount;
virtual ~EnumTableDefinition(); /* Call by this class only after the reference count is zero. */
};
#endif // __rtr_enumTableDefinition
| 33.061224 | 129 | 0.664198 | [
"object"
] |
bd9233aa740bbdd038574d11b91a5a65809ebe6e | 1,171 | h | C | opencv/line_feature/ImageFileLoader.h | gityf/img-video | 1a094475705cbe671da2a9aaad28d9817c379f14 | [
"Apache-2.0"
] | 25 | 2019-01-25T07:37:41.000Z | 2022-02-08T09:38:55.000Z | opencv/line_feature/ImageFileLoader.h | gityf/img-video | 1a094475705cbe671da2a9aaad28d9817c379f14 | [
"Apache-2.0"
] | 1 | 2020-02-14T09:18:46.000Z | 2020-02-17T03:10:14.000Z | opencv/line_feature/ImageFileLoader.h | gityf/img-video | 1a094475705cbe671da2a9aaad28d9817c379f14 | [
"Apache-2.0"
] | 22 | 2019-01-25T07:37:42.000Z | 2021-12-30T11:41:00.000Z | //
// Created by wangyaofu on 2019/2/20.
//
#ifndef UNTITLED_IMAGEFILELOADER_H
#define UNTITLED_IMAGEFILELOADER_H
#include <opencv2/opencv.hpp>
#include "../common/filesys.h"
#include "../common/timemeasurer.h"
class ImageFileLoader {
public:
ImageFileLoader() {}
virtual ~ImageFileLoader() {}
void init() {
doInit();
}
virtual void doInit() = 0;
void run(const char* path) {
std::vector<std::string> imgList;
common::FileSys::ListFiles(path, &imgList);
string fileName = "";
TimeMeasurer tm;
for (int j = 0; j < imgList.size(); ++j) {
tm.Reset();
fileName = path;
fileName += imgList[j];
cv::Mat src = imread(fileName, cv::IMREAD_ANYCOLOR);
if (src.empty()) {
continue;
}
tm.Reset();
handle(src);
std::cout << "cost=" << tm.Elapsed() << std::endl;
cv::imshow("res", src);
tm.Reset();
cv::waitKey(10);
getchar();
}
}
virtual void handle(cv::Mat& image) = 0;
};
#endif //UNTITLED_IMAGEFILELOADER_H
| 20.910714 | 64 | 0.526046 | [
"vector"
] |
ae66367a2e89535e2c03f5137d335e8c8933cb4b | 36,735 | h | C | base/include/vector.h | fizmat/AMGX | 11af85608ea0f4720e03cbcc920521745f9e40e5 | [
"BSD-3-Clause"
] | 278 | 2017-10-13T18:28:31.000Z | 2022-03-27T03:54:04.000Z | base/include/vector.h | fizmat/AMGX | 11af85608ea0f4720e03cbcc920521745f9e40e5 | [
"BSD-3-Clause"
] | 143 | 2017-10-18T10:30:34.000Z | 2022-03-30T21:13:16.000Z | base/include/vector.h | fizmat/AMGX | 11af85608ea0f4720e03cbcc920521745f9e40e5 | [
"BSD-3-Clause"
] | 112 | 2017-10-16T11:00:10.000Z | 2022-03-31T21:46:46.000Z | /* Copyright (c) 2011-2017, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
namespace amgx
{
/* NOTE: These enums are mostly used in distributed setting,
where the matrix is partitioned by sets of rows across distributed nodes.
Each distributed node contains a rectangular partition of the matrix,
defined by a set of rows belonging to this node.
The rows are reordered so that
interior rows - rows with no connections to other partitions - come first
boundary rows - rows with connections to other partitions - come second
halo rows - rows from other parttions to which the boundary rows were connected to - come last */
enum ViewType
{
INTERIOR = 1, /* only the interior rows (with no connections to other partitions) are seen */
BOUNDARY = 2, /* only the boundary rows (with connections to other partitions) are seen */
OWNED = 3, /* both the interior and boundary rows are seen */
HALO1 = 4, /* only the (first ring*) halo rows (rows from other partitions that are connected to the local boundary rows and that have been appended locally) are seen */
FULL = 7, /* all interior, boundary and halo rows are seen */
HALO2 = 8, /* only the (second ring) halo rows (rows from other partitions that are connected to the [first ring] halo rows and that have been appended locally) are seen */
ALL = 15 /* all interior, boundary and (first and second ring) halo rows are seen */
};
/* *: first and second ring refer to first and second degree neighbors in a graph associated with the current matrix. */
/* NOTE: These enums are mostly used in distributed setting.
They refer to properties of the vector, and are assigned to variable in_transfer below. */
enum TransferType
{
IDLE = 0, /* the vector is neither being send or received (default) */
SENDING = 1, /* Isend for the vector has been issued */
RECEIVING = 2 /* Irecv for the vector has been issued (often need to synchronize to make sure the transfer is finished) */
};
/* NOTE: These enums are used during coloring of the matrix (for incomplete factorizations, such as DILU, ILU0, etc.).
They refer to the order in which colors are assigned to the boundary (boundary_coloring) and halo (halo_coloring)
with respect to the colors used for the interior nodes. */
enum ColoringType
{
FIRST = 0, /* color the boundary/halo nodes first */
SYNC_COLORS = 1, /* color the boundary/halo and the interior nodes together at the same time */
LAST = 2 /* color the boundary/halo nodes last */
};
}
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <cusp/array1d.h>
#include <async_event.h>
#include <error.h>
#include <basic_types.h>
#include <resources.h>
#include <distributed/amgx_mpi.h>
#include <auxdata.h>
#include <amgx_types/pod_types.h>
#include "vector_thrust_allocator.h"
namespace amgx
{
const int sleep_us = 20;
// usleep for windows
#ifdef _WIN32
#include <Windows.h>
static void usleep(int waitTime)
{
LARGE_INTEGER time1;
LARGE_INTEGER time2;
LARGE_INTEGER freq;
QueryPerformanceCounter((LARGE_INTEGER *)&time1);
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
do
{
QueryPerformanceCounter((LARGE_INTEGER *)&time2);
}
while ( (time2.QuadPart - time1.QuadPart) * 1000000.0 / freq.QuadPart < waitTime);
}
#endif
template <class T_Config> class Vector;
template <class TConfig> class DistributedManager;
//Vector wrapping class which automatically performs indexing algerbra
template <class value_type, class index_type>
class PODVector
{
typedef index_type IndexType;
typedef index_type ValueType;
public:
__device__ __host__ inline PODVector(value_type *ptr, index_type block_dimy, index_type block_dimx) : ptr(ptr), block_size(block_dimx * block_dimy), block_dimx(block_dimx) {}
__device__ __host__ inline PODVector(const value_type *ptr, index_type block_dimy, index_type block_dimx) : ptr(ptr), block_size(block_dimx * block_dimy), block_dimx(block_dimx) {}
//access operators
__device__ __host__ inline value_type &operator[](index_type idx) { return ptr[idx]; }
__device__ __host__ inline value_type &operator()(index_type k, index_type i = 0, index_type j = 0) { return ptr[k * block_size + i * block_dimx + j]; }
__device__ __host__ inline short get_block_dimx() const { return block_dimx; }
__device__ __host__ inline short get_block_dimy() const { return block_size / block_dimx; }
__device__ __host__ inline short get_block_size() const { return block_size; }
private:
value_type *ptr;
short block_size; //=block_dimx*block_dimy
short block_dimx;
//const short block_dimy; //Not stored
};
//Vector wrapping class which automatically performs indexing algerbra
template <class value_type, class index_type>
class constPODVector
{
typedef index_type IndexType;
typedef index_type ValueType;
public:
__device__ __host__ inline constPODVector(const value_type *ptr, index_type block_dimy, index_type block_dimx) : ptr(ptr), block_size(block_dimx * block_dimy), block_dimx(block_dimx) {}
//access operators
__device__ __host__ inline const value_type &operator[](index_type idx) const { return ptr[idx]; }
__device__ __host__ inline const value_type &operator()(index_type k, index_type i = 0, index_type j = 0) const { return ptr[k * block_size + i * block_dimx + j]; }
__device__ __host__ inline short get_block_dimx() const { return block_dimx; }
__device__ __host__ inline short get_block_dimy() const { return block_size / block_dimx; }
__device__ __host__ inline short get_block_size() const { return block_size; }
private:
const value_type *ptr;
const short block_size; //=block_dimx*block_dimy;
const short block_dimx;
//const short block_dimy; //Not stored
};
// specialization for host
template <AMGX_VecPrecision t_vecPrec, AMGX_MatPrecision t_matPrec, AMGX_IndPrecision t_indPrec>
class Vector<TemplateConfig<AMGX_host, t_vecPrec, t_matPrec, t_indPrec> > : public thrust::host_vector<typename VecPrecisionMap<t_vecPrec>::Type>
{
typedef typename MemorySpaceMap<AMGX_host>::Type host_memory;
typedef typename MemorySpaceMap<AMGX_device>::Type device_memory;
public:
typedef TemplateConfig<AMGX_host, t_vecPrec, t_matPrec, t_indPrec> TConfig;
typedef TemplateConfig<AMGX_host, t_vecPrec, t_matPrec, t_indPrec> TConfig_h;
typedef TemplateConfig<AMGX_device, t_vecPrec, t_matPrec, t_indPrec> TConfig_d;
typedef typename TConfig::MemSpace memory_space;
typedef typename TConfig::VecPrec value_type;
typedef typename TConfig::IndPrec index_type;
typedef cusp::array1d_format format;
Vector() : block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_host_buffer(NULL), explicit_buffer_size(0), m_unconsolidated_size(0), m_resources(0) { };
inline Vector(unsigned int N) : thrust::host_vector<value_type>(N), block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(unsigned int N, value_type v) : thrust::host_vector<value_type>(N, v), block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(const Vector<TConfig_h> &a) : thrust::host_vector<value_type>(a), block_dimx(a.get_block_dimx()), block_dimy(a.get_block_dimy()), num_rows(a.get_num_rows()), num_cols(a.get_num_cols()), lda(a.get_lda()), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(const Vector<TConfig_d> &a) : thrust::host_vector<value_type>(a), block_dimx(a.get_block_dimx()), block_dimy(a.get_block_dimy()), num_rows(a.get_num_rows()), num_cols(a.get_num_cols()), lda(a.get_lda()), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
~Vector()
{
#ifdef AMGX_WITH_MPI
if (requests.size() && in_transfer != IDLE)
{
//if async host-copy comms module is being used, signal deallocation and wait until communications are finished/canceled
if (explicit_host_buffer != NULL && (in_transfer & RECEIVING))
{
cancel = 1;
while (cancel) {usleep(5);}
}
else
{
for (unsigned int i = 0; i < requests.size(); i++)
{
if ((i < requests.size() / 2 && (in_transfer & SENDING)) || (i >= requests.size() / 2 && (in_transfer & RECEIVING)))
{
MPI_Cancel(&requests[i]);
}
}
MPI_Waitall((int)requests.size(), &requests[0], &statuses[0]);
}
}
#endif
if (buffer != NULL) { delete buffer; }
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
}
if (host_send_recv_buffer != NULL) { delete host_send_recv_buffer; }
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
cudaEventDestroy(mpi_event);
}
}
operator PODVector<value_type, index_type>() { return PODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
operator constPODVector<value_type, index_type>() const { return constPODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
PODVector<value_type, index_type> pod() { return PODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
constPODVector<value_type, index_type> const_pod() const { return constPODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
template< typename OtherVector >
inline void copy( const OtherVector &a )
{
//copy dimensions
this->set_block_dimx( a.get_block_dimx());
this->set_block_dimy( a.get_block_dimy());
this->set_num_rows(a.get_num_rows());
this->set_num_cols(a.get_num_cols());
this->set_lda(a.get_lda());
this->resize(a.size(), value_type());
//copy data
this->assign( a.begin( ), a.end( ) );
//reset distributed flags and buffers
if (tag == -1) { tag = a.tag; }
in_transfer = IDLE;
dirtybit = a.dirtybit;
if (buffer != NULL)
{
delete buffer;
buffer = NULL;
buffer_size = 0;
}
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
linear_buffers_size = 0;
}
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
explicit_host_buffer = NULL;
explicit_buffer_size = 0;
cudaEventDestroy(mpi_event);
}
}
//inline void copy_async(const Vector<ScalarType,host_memory> & a) { ... } No host to host asynchronous copy
inline void copy_async(const Vector<TConfig_d> &a, cudaStream_t s = 0)
{
//copy dimensions
this->set_block_dimx( a.get_block_dimx());
this->set_block_dimy( a.get_block_dimy());
this->set_num_rows(a.get_num_rows());
this->set_num_cols(a.get_num_cols());
this->set_lda(a.get_lda());
this->resize(a.size(), value_type());
//copy data
cudaMemcpyAsync(raw(), a.raw(), bytes(), cudaMemcpyDefault, s);
event.record();
//reset distributed flags and buffers
if (tag == -1) { tag = a.tag; }
in_transfer = IDLE;
dirtybit = a.dirtybit;
if (buffer != NULL)
{
delete buffer;
buffer = NULL;
buffer_size = 0;
}
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
linear_buffers_size = 0;
}
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
explicit_host_buffer = NULL;
explicit_buffer_size = 0;
cudaEventDestroy(mpi_event);
}
}
inline void sync() { event.sync(); }
inline Vector<TConfig_h> &operator=(const cusp::array1d<value_type, host_memory> &a) { copy(a); return *this; }
inline Vector<TConfig_h> &operator=(const cusp::array1d<value_type, device_memory> &a) { copy(a); return *this; }
inline Vector<TConfig_h> &operator=(const Vector<TConfig_h> &a) { copy(a); return *this; }
inline Vector<TConfig_h> &operator=(const Vector<TConfig_d> &a) { copy(a); return *this; }
inline value_type *raw()
{
if (bytes() > 0) { return thrust::raw_pointer_cast(this->data()); }
else { return 0; }
}
inline const value_type *raw() const
{
if (bytes() > 0) { return thrust::raw_pointer_cast(this->data()); }
else { return 0; }
}
inline short get_block_size() const { return block_dimx * block_dimy; }
inline short get_block_dimx() const { return block_dimx; }
inline short get_block_dimy() const { return block_dimy; }
inline void set_block_dimx(short dimx) { block_dimx = dimx; }
inline void set_block_dimy(short dimy) { block_dimy = dimy; }
int get_num_cols() const { return num_cols; }
int get_num_rows() const { return num_rows; }
int get_lda() const { return lda; }
void set_num_rows(int size) { num_rows = size; }
void set_num_cols(int size) { num_cols = size; }
void set_lda(int size) { lda = size; }
inline size_t bytes(bool device_only = false) const
{
size_t res = 0;
if (!device_only)
{
res = this->size() * sizeof(value_type);
}
return res;
}
void printConfig()
{
printf("Configuration: %s, %s, %s, %s\n",
TConfig::MemSpaceInfo::getName(),
TConfig::VecPrecInfo::getName(),
TConfig::MatPrecInfo::getName(),
TConfig::IndPrecInfo::getName());
}
void init_host_send_recv_buffer() { host_send_recv_buffer = new Vector<TConfig_h>(this->size()); }
value_type **linear_buffers;
int linear_buffers_size;
thrust::host_vector<value_type *> linear_buffers_ptrs;
Vector<TemplateConfig<AMGX_host, t_vecPrec, t_matPrec, t_indPrec> > *buffer;
Vector<TConfig_h> *host_send_recv_buffer;
void setManager(DistributedManager<TConfig> &manager) { this->manager = &manager; }
void unsetManager() { this->manager = NULL;}
DistributedManager<TConfig> *getManager() const {return manager;}
void unset_transformed() {v_is_transformed = false;}
void set_transformed() {v_is_transformed = true;}
void set_unconsolidated_size(int size) {m_unconsolidated_size = size;}
int get_unconsolidated_size() { return m_unconsolidated_size;}
bool is_transformed() { return v_is_transformed;}
void set_is_vector_read_partitioned(bool is_read_partitioned) {v_is_read_partitioned = is_read_partitioned;}
inline bool is_vector_read_partitioned() const {return v_is_read_partitioned;}
inline Resources *getResources() const { return m_resources; }
inline void setResources(Resources *resources) { m_resources = resources; }
int tag;
volatile int dirtybit;
volatile int cancel; //Signals to the async host-copy comms module that vector is being deallocated
int delayed_send;
unsigned int in_transfer;
int m_unconsolidated_size;
std::vector<value_type> host_buffer;
value_type *explicit_host_buffer; //A separate pinned memory buffer to be used by async host-copy comms module
int explicit_buffer_size;
int buffer_size;
cudaEvent_t mpi_event;
#ifdef AMGX_WITH_MPI
std::vector<MPI_Request> requests;
std::vector<MPI_Status> statuses;
std::vector<MPI_Request> send_requests;
std::vector<MPI_Request> recv_requests;
std::vector<MPI_Status> send_statuses;
std::vector<MPI_Status> recv_statuses;
#endif
private:
AsyncEvent event;
short block_dimx, block_dimy;
unsigned int num_rows, num_cols, lda;
bool v_is_transformed;
bool v_is_read_partitioned;
DistributedManager<TConfig> *manager;
Resources *m_resources;
};
// specialization for device
template <AMGX_VecPrecision t_vecPrec, AMGX_MatPrecision t_matPrec, AMGX_IndPrecision t_indPrec>
class Vector<TemplateConfig<AMGX_device, t_vecPrec, t_matPrec, t_indPrec> > : public device_vector_alloc<typename VecPrecisionMap<t_vecPrec>::Type>
{
typedef typename MemorySpaceMap<AMGX_host>::Type host_memory;
typedef typename MemorySpaceMap<AMGX_device>::Type device_memory;
public:
typedef TemplateConfig<AMGX_device, t_vecPrec, t_matPrec, t_indPrec> TConfig;
typedef TemplateConfig<AMGX_host, t_vecPrec, t_matPrec, t_indPrec> TConfig_h;
typedef TemplateConfig<AMGX_device, t_vecPrec, t_matPrec, t_indPrec> TConfig_d;
typedef typename TConfig::MemSpace memory_space;
typedef typename TConfig::VecPrec value_type;
typedef typename TConfig::IndPrec index_type;
typedef cusp::array1d_format format;
Vector() : block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(unsigned int N) : device_vector_alloc<value_type>(N), block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(unsigned int N, int dimx, int dimy) : device_vector_alloc<value_type>(N), block_dimx(dimx), block_dimy(dimy), num_rows(0), num_cols(1), lda(0), buffer(NULL), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(unsigned int N, value_type v) : device_vector_alloc<value_type>(N, v), block_dimx(1), block_dimy(1), num_rows(0), num_cols(1), lda(0), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(const Vector<TConfig_h> &a) : device_vector_alloc<value_type>(a), block_dimx(a.get_block_dimx()), block_dimy(a.get_block_dimy()), num_rows(a.get_num_rows()), num_cols(a.get_num_cols()), lda(a.get_lda()), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
inline Vector(const Vector<TConfig_d> &a) : device_vector_alloc<value_type>(a), block_dimx(a.get_block_dimx()), block_dimy(a.get_block_dimy()), num_rows(a.get_num_rows()), num_cols(a.get_num_cols()), lda(a.get_lda()), buffer(NULL), buffer_size(0), dirtybit(1), in_transfer(IDLE), tag(-1), delayed_send(1), cancel(0), manager(NULL), v_is_transformed(false), v_is_read_partitioned(false), host_send_recv_buffer(NULL), linear_buffers_size(0), explicit_buffer_size(0), explicit_host_buffer(NULL), m_unconsolidated_size(0), m_resources(0) {}
~Vector()
{
#ifdef AMGX_WITH_MPI
if (requests.size() && in_transfer != IDLE)
{
//if async host-copy comms module is being used, signal deallocation and wait until communications are finished/canceled
if (explicit_host_buffer != NULL && (in_transfer & RECEIVING))
{
cancel = 1;
while (cancel) {usleep(5);}
}
else
{
for (unsigned int i = 0; i < requests.size(); i++)
{
if ((i < requests.size() / 2 && (in_transfer & SENDING)) || (i >= requests.size() / 2 && (in_transfer & RECEIVING)))
{
MPI_Cancel(&requests[i]);
}
}
MPI_Waitall((int)requests.size(), &requests[0], &statuses[0]);
}
}
#endif
if (buffer != NULL) { delete buffer; }
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
}
if (host_send_recv_buffer != NULL) { delete host_send_recv_buffer; }
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
cudaEventDestroy(mpi_event);
}
}
operator PODVector<value_type, index_type>() { return PODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
operator constPODVector<value_type, index_type>() const { return constPODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
PODVector<value_type, index_type> pod() { return PODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
constPODVector<value_type, index_type> const_pod() const { return constPODVector<value_type, index_type>(raw(), block_dimy, block_dimx); }
template< typename OtherVector >
inline void copy( const OtherVector &a )
{
//copy dimensions
this->set_block_dimx( a.get_block_dimx());
this->set_block_dimy( a.get_block_dimy());
this->set_num_rows(a.get_num_rows());
this->set_num_cols(a.get_num_cols());
this->set_lda(a.get_lda());
this->resize(a.size(), value_type());
//copy data
this->assign( a.begin( ), a.end( ) );
//reset distributed flags and buffers
if (tag == -1) { tag = a.tag; }
in_transfer = IDLE;
dirtybit = a.dirtybit;
if (buffer != NULL)
{
delete buffer;
buffer = NULL;
buffer_size = 0;
}
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
linear_buffers_size = 0;
}
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
explicit_host_buffer = NULL;
explicit_buffer_size = 0;
cudaEventDestroy(mpi_event);
}
}
inline void copy_async(const Vector<TConfig_h> &a, cudaStream_t s = 0)
{
//copy dimensions
this->set_block_dimx( a.get_block_dimx());
this->set_block_dimy( a.get_block_dimy());
this->set_num_rows(a.get_num_rows());
this->set_num_cols(a.get_num_cols());
this->set_lda(a.get_lda());
this->resize(a.size(), value_type());
//copy data
cudaMemcpyAsync(raw(), a.raw(), bytes(), cudaMemcpyDefault, s);
event.record();
//reset distributed flags and buffers
if (tag == -1) { tag = a.tag; }
in_transfer = IDLE;
dirtybit = a.dirtybit;
if (buffer != NULL)
{
delete buffer;
buffer = NULL;
buffer_size = 0;
}
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
linear_buffers_size = 0;
}
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
explicit_host_buffer = NULL;
explicit_buffer_size = 0;
cudaEventDestroy(mpi_event);
}
}
inline void copy_async(const Vector<TConfig_d> &a, cudaStream_t s = 0)
{
//copy dimensions
this->set_block_dimx( a.get_block_dimx());
this->set_block_dimy( a.get_block_dimy());
this->set_num_rows(a.get_num_rows());
this->set_num_cols(a.get_num_cols());
this->set_lda(a.get_lda());
this->resize(a.size(), value_type());
//copy data
cudaMemcpyAsync(raw(), a.raw(), bytes(), cudaMemcpyDefault, s);
event.record();
//reset distributed flags and buffers
if (tag == -1) { tag = a.tag; }
in_transfer = IDLE;
dirtybit = a.dirtybit;
if (buffer != NULL)
{
delete buffer;
buffer = NULL;
buffer_size = 0;
}
if (linear_buffers_size != 0)
{
amgx::memory::cudaFreeHost(&(linear_buffers[0]));
linear_buffers_size = 0;
}
if (explicit_host_buffer)
{
amgx::memory::cudaFreeHost(explicit_host_buffer);
explicit_host_buffer = NULL;
explicit_buffer_size = 0;
cudaEventDestroy(mpi_event);
}
}
inline void sync() { event.sync(); }
inline Vector<TConfig_d> &operator=(const cusp::array1d<value_type, host_memory> &a) { copy(a); return *this; }
inline Vector<TConfig_d> &operator=(const cusp::array1d<value_type, device_memory> &a) { copy(a); return *this; }
inline Vector<TConfig_d> &operator=(const Vector<TConfig_h> &a) { copy(a); return *this; }
inline Vector<TConfig_d> &operator=(const Vector<TConfig_d> &a) { copy(a); return *this; }
inline value_type *raw()
{
if (bytes() > 0) { return thrust::raw_pointer_cast(this->data()); }
else { return 0; }
}
inline const value_type *raw() const
{
if (bytes() > 0) { return thrust::raw_pointer_cast(this->data()); }
else { return 0; }
}
inline short get_block_size() const { return block_dimx * block_dimy; }
inline short get_block_dimx() const { return block_dimx; }
inline short get_block_dimy() const { return block_dimy; }
inline void set_block_dimx(short dimx) { block_dimx = dimx; }
inline void set_block_dimy(short dimy) { block_dimy = dimy; }
int get_num_rows() const { return num_rows; }
int get_num_cols() const { return num_cols; }
int get_lda() const { return lda; }
void set_num_rows(int size) { num_rows = size; }
void set_num_cols(int size) { num_cols = size; }
void set_lda(int size) { lda = size; }
inline size_t bytes(bool device_only = false) const
{
return this->size() * sizeof(value_type);
}
void printConfig()
{
printf("Configuration: %s, %s, %s, %s\n",
TConfig::MemSpaceInfo::getName(),
TConfig::VecPrecInfo::getName(),
TConfig::MatPrecInfo::getName(),
TConfig::IndPrecInfo::getName());
}
void setManager(DistributedManager<TConfig> &manager) { this->manager = &manager; }
void unsetManager() { this->manager = NULL;}
DistributedManager<TConfig> *getManager() const {return manager;}
void set_transformed() {v_is_transformed = true;}
void unset_transformed() {v_is_transformed = false;}
void set_unconsolidated_size(int size) {m_unconsolidated_size = size;}
int get_unconsolidated_size() { return m_unconsolidated_size;}
bool is_transformed() { return v_is_transformed;}
void set_is_vector_read_partitioned(bool is_read_partitioned) {v_is_read_partitioned = is_read_partitioned;}
inline bool is_vector_read_partitioned() const {return v_is_read_partitioned;}
inline Resources *getResources() const { return m_resources; }
inline void setResources(Resources *resources) { m_resources = resources; }
void init_host_send_recv_buffer() { host_send_recv_buffer = new Vector<TConfig_h>(this->size()); }
value_type **linear_buffers;
int linear_buffers_size;
device_vector_alloc<value_type *> linear_buffers_ptrs;
Vector<TemplateConfig<AMGX_device, t_vecPrec, t_matPrec, t_indPrec> > *buffer;
Vector<TConfig_h > *host_send_recv_buffer;
int tag;
volatile int dirtybit;
volatile int cancel; //Signals to the async host-copy comms module that vector is being deallocated
int delayed_send;
int m_unconsolidated_size;
unsigned int in_transfer;
std::vector<value_type> host_buffer;
value_type *explicit_host_buffer; //A separate pinned memory buffer to be used by async host-copy comms module
int explicit_buffer_size;
int buffer_size;
cudaEvent_t mpi_event;
#ifdef AMGX_WITH_MPI
std::vector<MPI_Request> requests;
std::vector<MPI_Status> statuses;
std::vector<MPI_Request> send_requests;
std::vector<MPI_Request> recv_requests;
std::vector<MPI_Status> send_statuses;
std::vector<MPI_Status> recv_statuses;
#endif
private:
DistributedManager<TConfig> *manager;
bool v_is_transformed;
bool v_is_read_partitioned; //distributed: need this to tell the partitioner the vector is coming from distributed reader
AsyncEvent event;
short block_dimx, block_dimy;
unsigned int num_rows, num_cols, lda;
Resources *m_resources;
};
} //end namespace amgx
extern "C" {
#define DEFINE_VECTOR_TYPES \
\
typedef Vector<TConfig> VVector;\
typedef typename TConfig::template setVecPrec<(AMGX_VecPrecision)AMGX_GET_MODE_VAL(AMGX_MatPrecision, TConfig::mode)>::Type mvec_value_type;\
typedef Vector<mvec_value_type> MVector;\
typedef typename TConfig::template setVecPrec<AMGX_vecInt>::Type ivec_value_type;\
typedef Vector<ivec_value_type> IVector;\
typedef typename TConfig::template setVecPrec<AMGX_vecInt64>::Type i64vec_value_type;\
typedef Vector<i64vec_value_type> I64Vector;\
typedef TemplateConfig<AMGX_host,TConfig::vecPrec,TConfig::matPrec,TConfig::indPrec> TConfig_h;\
typedef TemplateConfig<AMGX_device,TConfig::vecPrec,TConfig::matPrec,TConfig::indPrec> TConfig_d;\
typedef Vector<TConfig_d> VVector_d;\
typedef typename TConfig_d::template setVecPrec<(AMGX_VecPrecision)AMGX_GET_MODE_VAL(AMGX_MatPrecision, TConfig_d::mode)>::Type mvec_value_type_d;\
typedef Vector<mvec_value_type_d> MVector_d;\
typedef typename TConfig_d::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_d;\
typedef Vector<ivec_value_type_d> IVector_d;\
typedef typename TConfig_d::template setVecPrec<AMGX_vecInt64>::Type i64vec_value_type_d;\
typedef Vector<i64vec_value_type_d> I64Vector_d;\
typedef Vector<TConfig_h> VVector_h;\
typedef typename TConfig_h::template setVecPrec<(AMGX_VecPrecision)AMGX_GET_MODE_VAL(AMGX_MatPrecision, TConfig_h::mode)>::Type mvec_value_type_h;\
typedef Vector<mvec_value_type_h> MVector_h;\
typedef typename TConfig_h::template setVecPrec<AMGX_vecInt>::Type ivec_value_type_h;\
typedef Vector<ivec_value_type_h> IVector_h;\
typedef typename TConfig_h::template setVecPrec<AMGX_vecInt64>::Type i64vec_value_type_h;\
typedef Vector<i64vec_value_type_h> I64Vector_h;\
typedef TemplateConfig<TConfig::memSpace, types::PODTypes<typename VVector::value_type>::vec_prec, TConfig::matPrec, TConfig::indPrec> PODConfig;\
typedef Vector<PODConfig> POD_Vector;\
}
| 48.399209 | 545 | 0.636695 | [
"vector"
] |
ae74122a4b6fe4ecc664853407bd2ae572cc9a06 | 1,713 | h | C | Source/Tools/Parser/Sources/TypeInfo.h | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 27 | 2015-01-08T08:26:29.000Z | 2019-02-10T03:18:05.000Z | Source/Tools/Parser/Sources/TypeInfo.h | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 1 | 2017-04-05T02:02:14.000Z | 2017-04-05T02:02:14.000Z | Source/Tools/Parser/Sources/TypeInfo.h | RamilGauss/MMO-Framework | c7c97b019adad940db86d6533861deceafb2ba04 | [
"MIT"
] | 17 | 2015-01-18T02:50:01.000Z | 2019-02-08T21:00:53.000Z | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#pragma once
#include <vector>
#include <list>
#include <map>
#include <memory>
#include <array>
#include "MemberInfo.h"
#include "InheritanceInfo.h"
#include "MethodInfo.h"
namespace nsCppParser
{
struct DllExport TTypeInfo
{
std::string mFileName;
std::set<std::string> mPragmaTextSet;// #pragma TEXT
DeclarationType mType;
std::set<std::string> mEnumKeys;
std::vector<TInheritanceInfo> mInheritanceVec;
std::string mName;
std::vector<std::string> mNamespaceVec;
typedef std::shared_ptr<TMethodInfo> TMethodInfoPtr;
typedef std::vector<TMethodInfoPtr> TMethodInfoPtrVec;
typedef std::array<TMethodInfoPtrVec, (size_t)AccessLevel::COUNT> TAccessLevelMethodInfoPtrVecArray;
TAccessLevelMethodInfoPtrVecArray mMethods;
typedef std::shared_ptr<TMemberInfo> TMemberInfoPtr;
typedef std::vector<TMemberInfoPtr> TMemberInfoPtrVec;
typedef std::array<TMemberInfoPtrVec, (size_t)AccessLevel::COUNT> TAccessLevelMemberInfoPtrVecArray;
TAccessLevelMemberInfoPtrVecArray mMembers;
std::string GetNameSpace();// all namespaces: A::B::...::Z
std::string GetTypeNameWithNameSpace();// namespace::typename
std::string GetTypeNameWithNameSpaceAsVar();// namespace_typename
void AddMember(TMemberInfo& memberInfo);
void AddMethod(TMethodInfo& methodInfo);
void ClearMembers();
void ClearMethods();
};
} | 29.033898 | 109 | 0.682428 | [
"vector"
] |
ae7a99d84cb9166df277a44625798839f3d05ad8 | 7,615 | h | C | acados/sim/sim_irk_integrator.h | jkoendev/acados | 53b661f99e526d1bf5be166a9b552641df361219 | [
"BSD-2-Clause"
] | null | null | null | acados/sim/sim_irk_integrator.h | jkoendev/acados | 53b661f99e526d1bf5be166a9b552641df361219 | [
"BSD-2-Clause"
] | 1 | 2019-07-08T16:01:18.000Z | 2019-07-08T16:01:18.000Z | acados/sim/sim_irk_integrator.h | jkoendev/acados | 53b661f99e526d1bf5be166a9b552641df361219 | [
"BSD-2-Clause"
] | 4 | 2020-12-08T03:45:55.000Z | 2021-08-04T02:36:41.000Z | /*
* Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
* Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
* Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
* Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
*
* This file is part of acados.
*
* The 2-Clause BSD License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.;
*/
#ifndef ACADOS_SIM_SIM_IRK_INTEGRATOR_H_
#define ACADOS_SIM_SIM_IRK_INTEGRATOR_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "acados/sim/sim_common.h"
#include "acados/utils/types.h"
#include "blasfeo/include/blasfeo_common.h"
typedef struct
{
int nx;
int nu;
int nz;
} sim_irk_dims;
typedef struct
{
/* external functions */
// implicit fun - can either be fully implicit ode or dae
// - i.e. dae has z as additional last argument & nz > 0
external_function_generic *impl_ode_fun;
// implicit ode & jac_x & jax_xdot & jac_z
external_function_generic *impl_ode_fun_jac_x_xdot_z;
// jax_x & jac_xdot & jac_u & jac_z of implicit ode
external_function_generic *impl_ode_jac_x_xdot_u_z;
// hessian of implicit ode:
external_function_generic *impl_ode_hess;
} irk_model;
typedef struct
{
struct blasfeo_dvec *rG; // residuals of G (nx*ns)
struct blasfeo_dvec *K; // internal K variables ((nx+nz)*ns)
struct blasfeo_dvec *xt; // temporary x
struct blasfeo_dvec *xn; // x at each integration step
struct blasfeo_dvec xtdot; // temporary xdot
struct blasfeo_dvec *lambda; // adjoint sensitivities (nx + nu)
struct blasfeo_dvec *lambdaK; // auxiliary variable ((nx+nz)*ns) for adjoint propagation
struct blasfeo_dmat df_dx; // temporary Jacobian of ode w.r.t x (nx+nz, nx)
struct blasfeo_dmat df_dxdot; // temporary Jacobian of ode w.r.t xdot (nx+nz, nx)
struct blasfeo_dmat df_du; // temporary Jacobian of ode w.r.t u (nx+nz, nu)
struct blasfeo_dmat df_dz; // temporary Jacobian of ode w.r.t z (nx+nz, nu)
/* NOTE: the memory allocation corresponding to the following fields is CONDITIONAL */
// only allocated if (opts->sens_algebraic || opts->output_z)
int *ipiv_one_stage; // index of pivot vector (nx + nz)
double *Z_work; // used to perform computations to get out->zn (ns)
// df_dxdotz, dk0_dxu, only allocated if (opts->sens_algebraic)
// used for algebraic sensitivity generation
struct blasfeo_dmat df_dxdotz; // temporary Jacobian of ode w.r.t. xdot,z (nx+nz, nx+nz);
struct blasfeo_dmat dk0_dxu; // intermediate result, (nx+nz, nx+nu)
// dK_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused
// if ( opts->sens_hess) - array of (num_steps) blasfeo_dmat
// to store intermediate results
struct blasfeo_dmat *dK_dxu; // jacobian of (K,Z) over x and u ((nx+nz)*ns, nx+nu);
// S_forw: if (!opts->sens_hess) - single blasfeo_dmat that is reused
// if ( opts->sens_hess) - array of (num_steps + 1) blasfeo_dmat
// to store intermediate results
struct blasfeo_dmat *S_forw; // forward sensitivities (nx, nx+nu)
// dG_dxu: if (!opts->sens_hess) - single blasfeo_dmat that is reused
// if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results
struct blasfeo_dmat *dG_dxu; // jacobian of G over x and u ((nx+nz)*ns, nx+nu)
// dG_dK: if (!opts->sens_hess) - single blasfeo_dmat that is reused
// if ( opts->sens_hess) - array of blasfeo_dmat to store intermediate results
struct blasfeo_dmat *dG_dK; // jacobian of G over K ((nx+nz)*ns, (nx+nz)*ns)
// ipiv: index of pivot vector
// if (!opts->sens_hess) - array (ns * (nx + nz)) that is reused
// if ( opts->sens_hess) - array (ns * (nx + nz)) * num_steps, to store all
// pivot vectors for dG_dxu
int *ipiv; // index of pivot vector
// xn_traj, K_traj only available if( opts->sens_adj || opts->sens_hess )
struct blasfeo_dvec *xn_traj; // xn trajectory
struct blasfeo_dvec *K_traj; // K trajectory
/* the following variables are only available if (opts->sens_hess) */
// For Hessian propagation
struct blasfeo_dmat Hess; // temporary Hessian (nx + nu, nx + nu)
// output of impl_ode_hess
struct blasfeo_dmat f_hess; // size: (nx + nu, nx + nu)
struct blasfeo_dmat dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu)
struct blasfeo_dmat tmp_dxkzu_dw0; // size (2*nx + nu + nz) x (nx + nu)
} sim_irk_workspace;
typedef struct
{
double *xdot; // xdot[NX] - initialization for state derivatives k within the integrator
double *z; // z[NZ] - initialization for algebraic variables z
} sim_irk_memory;
// get & set functions
void sim_irk_dims_set(void *config_, void *dims_, const char *field, const int *value);
void sim_irk_dims_get(void *config_, void *dims_, const char *field, int* value);
// dims
int sim_irk_dims_calculate_size();
void *sim_irk_dims_assign(void *config_, void *raw_memory);
// model
int sim_irk_model_calculate_size(void *config, void *dims);
void *sim_irk_model_assign(void *config, void *dims, void *raw_memory);
int sim_irk_model_set(void *model, const char *field, void *value);
// opts
int sim_irk_opts_calculate_size(void *config, void *dims);
void *sim_irk_opts_assign(void *config, void *dims, void *raw_memory);
void sim_irk_opts_initialize_default(void *config, void *dims, void *opts_);
void sim_irk_opts_update(void *config_, void *dims, void *opts_);
int sim_irk_opts_set(void *config_, void *opts_, const char *field, void *value);
// memory
int sim_irk_memory_calculate_size(void *config, void *dims, void *opts_);
void *sim_irk_memory_assign(void *config, void *dims, void *opts_, void *raw_memory);
int sim_irk_memory_set(void *config_, void *dims_, void *mem_, const char *field, void *value);
// workspace
int sim_irk_workspace_calculate_size(void *config, void *dims, void *opts_);
void sim_irk_config_initialize_default(void *config);
// main
int sim_irk(void *config, sim_in *in, sim_out *out, void *opts_, void *mem_, void *work_);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // ACADOS_SIM_SIM_IRK_INTEGRATOR_H_
| 41.38587 | 95 | 0.700591 | [
"vector",
"model"
] |
ae7b43d42872f05007f442d23b4c74dd93f3929c | 666 | h | C | libep/public/include/ep/cpp/internal/i/iarraybuffer.h | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | libep/public/include/ep/cpp/internal/i/iarraybuffer.h | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | libep/public/include/ep/cpp/internal/i/iarraybuffer.h | Euclideon/udshell | 795e2d832429c8e5e47196742afc4b452aa23ec3 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _EP_IARRAYBUFFER_HPP
#define _EP_IARRAYBUFFER_HPP
#include "ep/cpp/component/component.h"
namespace ep {
class IArrayBuffer
{
public:
virtual void Allocate(SharedString _elementType, size_t _elementSize, Slice<const size_t> _shape) = 0;
virtual bool ReshapeInternal(Slice<const size_t> shape, bool copy) = 0;
virtual SharedString GetElementType() const = 0;
virtual size_t GetElementSize() const = 0;
virtual size_t GetNumDimensions() const = 0;
virtual size_t GetLength() const = 0;
virtual Slice<const size_t> GetShape() const = 0;
virtual Variant Save() const = 0;
};
} // namespace ep
#endif // _EP_IARRAYBUFFER_HPP
| 22.965517 | 104 | 0.749249 | [
"shape"
] |
ae7f8c7e070fa72ca33716e9bfe78c3cbbce8e37 | 2,668 | h | C | src/blinkit/blink/renderer/core/animation/InterpolationEffect.h | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 13 | 2020-04-21T13:14:00.000Z | 2021-11-13T14:55:12.000Z | src/blinkit/blink/renderer/core/animation/InterpolationEffect.h | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | null | null | null | src/blinkit/blink/renderer/core/animation/InterpolationEffect.h | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 4 | 2020-04-21T13:15:43.000Z | 2021-11-13T14:55:00.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef InterpolationEffect_h
#define InterpolationEffect_h
#include "core/CoreExport.h"
#include "core/animation/Interpolation.h"
#include "core/animation/Keyframe.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/animation/TimingFunction.h"
#include "wtf/PassOwnPtr.h"
namespace blink {
class CORE_EXPORT InterpolationEffect : public RefCounted<InterpolationEffect> {
public:
static PassRefPtr<InterpolationEffect> create()
{
return adoptRef(new InterpolationEffect());
}
void getActiveInterpolations(double fraction, double iterationDuration, Vector<RefPtr<Interpolation>>&) const;
void addInterpolation(PassRefPtr<Interpolation> interpolation, PassRefPtr<TimingFunction> easing, double start, double end, double applyFrom, double applyTo)
{
m_interpolations.append(InterpolationRecord::create(interpolation, easing, start, end, applyFrom, applyTo));
}
void addInterpolationsFromKeyframes(PropertyHandle, Element*, const ComputedStyle* baseStyle, Keyframe::PropertySpecificKeyframe& keyframeA, Keyframe::PropertySpecificKeyframe& keyframeB, double applyFrom, double applyTo);
template<typename T>
inline void forEachInterpolation(const T& callback)
{
for (auto& record : m_interpolations)
callback(*record->m_interpolation);
}
private:
InterpolationEffect()
{
}
class InterpolationRecord : public RefCounted<InterpolationRecord> {
public:
RefPtr<Interpolation> m_interpolation;
RefPtr<TimingFunction> m_easing;
double m_start;
double m_end;
double m_applyFrom;
double m_applyTo;
static PassRefPtr<InterpolationRecord> create(PassRefPtr<Interpolation> interpolation, PassRefPtr<TimingFunction> easing, double start, double end, double applyFrom, double applyTo)
{
return adoptRef(new InterpolationRecord(interpolation, easing, start, end, applyFrom, applyTo));
}
private:
InterpolationRecord(PassRefPtr<Interpolation> interpolation, PassRefPtr<TimingFunction> easing, double start, double end, double applyFrom, double applyTo)
: m_interpolation(interpolation)
, m_easing(easing)
, m_start(start)
, m_end(end)
, m_applyFrom(applyFrom)
, m_applyTo(applyTo)
{
}
};
Vector<RefPtr<InterpolationRecord>> m_interpolations;
};
} // namespace blink
#endif // InterpolationEffect_h
| 34.649351 | 226 | 0.721889 | [
"vector"
] |
ae9673f3a337e2ac5ae35cd6c2744b0ab274b354 | 1,216 | h | C | include/april/Cursor.h | borisblizzard/april | 924a4fd770508bc87ac67b49b022c9905f94db32 | [
"BSD-3-Clause"
] | null | null | null | include/april/Cursor.h | borisblizzard/april | 924a4fd770508bc87ac67b49b022c9905f94db32 | [
"BSD-3-Clause"
] | null | null | null | include/april/Cursor.h | borisblizzard/april | 924a4fd770508bc87ac67b49b022c9905f94db32 | [
"BSD-3-Clause"
] | null | null | null | /// @file
/// @version 5.2
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
///
/// @section DESCRIPTION
///
/// Defines a Cursor object.
#ifndef APRIL_CURSOR_H
#define APRIL_CURSOR_H
#include <hltypes/hltypesUtil.h>
#include <hltypes/hstring.h>
#include "aprilExport.h"
namespace april
{
class Window;
/// @brief Defines a cursor object.
class aprilExport Cursor
{
public:
friend class Window;
/// @brief The filename of the cursor file.
HL_DEFINE_GET(hstr, filename, Filename);
protected:
/// @brief The filename of the cursor file.
hstr filename;
/// @brief Whether loaded from a resource file or a normal file.
bool fromResource;
/// @brief Basic constructor.
/// @param[in] fromResource Whether loaded from a resource file or a normal file.
Cursor(bool fromResource);
/// @brief Destructor.
virtual ~Cursor();
/// @brief Creates an internal curosr object from a filename.
/// @param[in] filename The filename to load.
/// @return True if loading was successful.
virtual bool _create(chstr filename);
};
}
#endif
| 21.714286 | 83 | 0.697368 | [
"object"
] |
ae9895c537c51764abe82ad08d8318799ee0b7e9 | 26,087 | h | C | pytorch-frontend/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h | AndreasKaratzas/stonne | 2915fcc46cc94196303d81abbd1d79a56d6dd4a9 | [
"MIT"
] | 40 | 2021-06-01T07:37:59.000Z | 2022-03-25T01:42:09.000Z | pytorch-frontend/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h | AndreasKaratzas/stonne | 2915fcc46cc94196303d81abbd1d79a56d6dd4a9 | [
"MIT"
] | 14 | 2021-06-01T11:52:46.000Z | 2022-03-25T02:13:08.000Z | pytorch-frontend/third_party/protobuf/ruby/ext/google/protobuf_c/protobuf.h | AndreasKaratzas/stonne | 2915fcc46cc94196303d81abbd1d79a56d6dd4a9 | [
"MIT"
] | 7 | 2021-07-20T19:34:26.000Z | 2022-03-13T21:07:36.000Z | // Protocol Buffers - Google's data interchange format
// Copyright 2014 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef __GOOGLE_PROTOBUF_RUBY_PROTOBUF_H__
#define __GOOGLE_PROTOBUF_RUBY_PROTOBUF_H__
#include <ruby/ruby.h>
#include <ruby/vm.h>
#include <ruby/encoding.h>
#include "upb.h"
// Forward decls.
struct DescriptorPool;
struct Descriptor;
struct FileDescriptor;
struct FieldDescriptor;
struct EnumDescriptor;
struct MessageLayout;
struct MessageField;
struct MessageHeader;
struct MessageBuilderContext;
struct EnumBuilderContext;
struct FileBuilderContext;
struct Builder;
typedef struct DescriptorPool DescriptorPool;
typedef struct Descriptor Descriptor;
typedef struct FileDescriptor FileDescriptor;
typedef struct FieldDescriptor FieldDescriptor;
typedef struct OneofDescriptor OneofDescriptor;
typedef struct EnumDescriptor EnumDescriptor;
typedef struct MessageLayout MessageLayout;
typedef struct MessageField MessageField;
typedef struct MessageOneof MessageOneof;
typedef struct MessageHeader MessageHeader;
typedef struct MessageBuilderContext MessageBuilderContext;
typedef struct OneofBuilderContext OneofBuilderContext;
typedef struct EnumBuilderContext EnumBuilderContext;
typedef struct FileBuilderContext FileBuilderContext;
typedef struct Builder Builder;
/*
It can be a bit confusing how the C structs defined below and the Ruby
objects interact and hold references to each other. First, a few principles:
- Ruby's "TypedData" abstraction lets a Ruby VALUE hold a pointer to a C
struct (or arbitrary memory chunk), own it, and free it when collected.
Thus, each struct below will have a corresponding Ruby object
wrapping/owning it.
- To get back from an underlying upb {msg,enum}def to the Ruby object, we
keep a global hashmap, accessed by get_def_obj/add_def_obj below.
The in-memory structure is then something like:
Ruby | upb
|
DescriptorPool ------------|-----------> upb_symtab____________________
| | (message types) \
| v \
Descriptor ---------------|-----------> upb_msgdef (enum types)|
|--> msgclass | | ^ |
| (dynamically built) | | | (submsg fields) |
|--> MessageLayout | | | /
|--------------------------|> decoder method| | /
\--------------------------|> serialize | | /
| handlers v | /
FieldDescriptor -----------|-----------> upb_fielddef /
| | /
| v (enum fields) /
EnumDescriptor ------------|-----------> upb_enumdef <----------'
|
|
^ | \___/
`---------------|-----------------' (get_def_obj map)
*/
// -----------------------------------------------------------------------------
// Ruby class structure definitions.
// -----------------------------------------------------------------------------
struct DescriptorPool {
VALUE def_to_descriptor; // Hash table of def* -> Ruby descriptor.
upb_symtab* symtab;
upb_handlercache* fill_handler_cache;
upb_handlercache* pb_serialize_handler_cache;
upb_handlercache* json_serialize_handler_cache;
upb_handlercache* json_serialize_handler_preserve_cache;
upb_pbcodecache* fill_method_cache;
upb_json_codecache* json_fill_method_cache;
};
struct Descriptor {
const upb_msgdef* msgdef;
MessageLayout* layout;
VALUE klass;
VALUE descriptor_pool;
};
struct FileDescriptor {
const upb_filedef* filedef;
VALUE descriptor_pool; // Owns the upb_filedef.
};
struct FieldDescriptor {
const upb_fielddef* fielddef;
VALUE descriptor_pool; // Owns the upb_fielddef.
};
struct OneofDescriptor {
const upb_oneofdef* oneofdef;
VALUE descriptor_pool; // Owns the upb_oneofdef.
};
struct EnumDescriptor {
const upb_enumdef* enumdef;
VALUE module; // begins as nil
VALUE descriptor_pool; // Owns the upb_enumdef.
};
struct MessageBuilderContext {
google_protobuf_DescriptorProto* msg_proto;
VALUE file_builder;
};
struct OneofBuilderContext {
int oneof_index;
VALUE message_builder;
};
struct EnumBuilderContext {
google_protobuf_EnumDescriptorProto* enum_proto;
VALUE file_builder;
};
struct FileBuilderContext {
upb_arena *arena;
google_protobuf_FileDescriptorProto* file_proto;
VALUE descriptor_pool;
};
struct Builder {
VALUE descriptor_pool;
VALUE default_file_builder;
};
extern VALUE cDescriptorPool;
extern VALUE cDescriptor;
extern VALUE cFileDescriptor;
extern VALUE cFieldDescriptor;
extern VALUE cEnumDescriptor;
extern VALUE cMessageBuilderContext;
extern VALUE cOneofBuilderContext;
extern VALUE cEnumBuilderContext;
extern VALUE cFileBuilderContext;
extern VALUE cBuilder;
extern VALUE cError;
extern VALUE cParseError;
extern VALUE cTypeError;
// We forward-declare all of the Ruby method implementations here because we
// sometimes call the methods directly across .c files, rather than going
// through Ruby's method dispatching (e.g. during message parse). It's cleaner
// to keep the list of object methods together than to split them between
// static-in-file definitions and header declarations.
void DescriptorPool_mark(void* _self);
void DescriptorPool_free(void* _self);
VALUE DescriptorPool_alloc(VALUE klass);
void DescriptorPool_register(VALUE module);
DescriptorPool* ruby_to_DescriptorPool(VALUE value);
VALUE DescriptorPool_build(int argc, VALUE* argv, VALUE _self);
VALUE DescriptorPool_lookup(VALUE _self, VALUE name);
VALUE DescriptorPool_generated_pool(VALUE _self);
extern VALUE generated_pool;
void Descriptor_mark(void* _self);
void Descriptor_free(void* _self);
VALUE Descriptor_alloc(VALUE klass);
void Descriptor_register(VALUE module);
Descriptor* ruby_to_Descriptor(VALUE value);
VALUE Descriptor_initialize(VALUE _self, VALUE cookie, VALUE descriptor_pool,
VALUE ptr);
VALUE Descriptor_name(VALUE _self);
VALUE Descriptor_each(VALUE _self);
VALUE Descriptor_lookup(VALUE _self, VALUE name);
VALUE Descriptor_each_oneof(VALUE _self);
VALUE Descriptor_lookup_oneof(VALUE _self, VALUE name);
VALUE Descriptor_msgclass(VALUE _self);
VALUE Descriptor_file_descriptor(VALUE _self);
extern const rb_data_type_t _Descriptor_type;
void FileDescriptor_mark(void* _self);
void FileDescriptor_free(void* _self);
VALUE FileDescriptor_alloc(VALUE klass);
void FileDescriptor_register(VALUE module);
FileDescriptor* ruby_to_FileDescriptor(VALUE value);
VALUE FileDescriptor_initialize(VALUE _self, VALUE cookie,
VALUE descriptor_pool, VALUE ptr);
VALUE FileDescriptor_name(VALUE _self);
VALUE FileDescriptor_syntax(VALUE _self);
void FieldDescriptor_mark(void* _self);
void FieldDescriptor_free(void* _self);
VALUE FieldDescriptor_alloc(VALUE klass);
void FieldDescriptor_register(VALUE module);
FieldDescriptor* ruby_to_FieldDescriptor(VALUE value);
VALUE FieldDescriptor_initialize(VALUE _self, VALUE cookie,
VALUE descriptor_pool, VALUE ptr);
VALUE FieldDescriptor_name(VALUE _self);
VALUE FieldDescriptor_type(VALUE _self);
VALUE FieldDescriptor_default(VALUE _self);
VALUE FieldDescriptor_label(VALUE _self);
VALUE FieldDescriptor_number(VALUE _self);
VALUE FieldDescriptor_submsg_name(VALUE _self);
VALUE FieldDescriptor_subtype(VALUE _self);
VALUE FieldDescriptor_has(VALUE _self, VALUE msg_rb);
VALUE FieldDescriptor_clear(VALUE _self, VALUE msg_rb);
VALUE FieldDescriptor_get(VALUE _self, VALUE msg_rb);
VALUE FieldDescriptor_set(VALUE _self, VALUE msg_rb, VALUE value);
upb_fieldtype_t ruby_to_fieldtype(VALUE type);
VALUE fieldtype_to_ruby(upb_fieldtype_t type);
void OneofDescriptor_mark(void* _self);
void OneofDescriptor_free(void* _self);
VALUE OneofDescriptor_alloc(VALUE klass);
void OneofDescriptor_register(VALUE module);
OneofDescriptor* ruby_to_OneofDescriptor(VALUE value);
VALUE OneofDescriptor_initialize(VALUE _self, VALUE cookie,
VALUE descriptor_pool, VALUE ptr);
VALUE OneofDescriptor_name(VALUE _self);
VALUE OneofDescriptor_each(VALUE _self);
void EnumDescriptor_mark(void* _self);
void EnumDescriptor_free(void* _self);
VALUE EnumDescriptor_alloc(VALUE klass);
VALUE EnumDescriptor_initialize(VALUE _self, VALUE cookie,
VALUE descriptor_pool, VALUE ptr);
void EnumDescriptor_register(VALUE module);
EnumDescriptor* ruby_to_EnumDescriptor(VALUE value);
VALUE EnumDescriptor_file_descriptor(VALUE _self);
VALUE EnumDescriptor_name(VALUE _self);
VALUE EnumDescriptor_lookup_name(VALUE _self, VALUE name);
VALUE EnumDescriptor_lookup_value(VALUE _self, VALUE number);
VALUE EnumDescriptor_each(VALUE _self);
VALUE EnumDescriptor_enummodule(VALUE _self);
extern const rb_data_type_t _EnumDescriptor_type;
void MessageBuilderContext_mark(void* _self);
void MessageBuilderContext_free(void* _self);
VALUE MessageBuilderContext_alloc(VALUE klass);
void MessageBuilderContext_register(VALUE module);
MessageBuilderContext* ruby_to_MessageBuilderContext(VALUE value);
VALUE MessageBuilderContext_initialize(VALUE _self,
VALUE _file_builder,
VALUE name);
VALUE MessageBuilderContext_optional(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_required(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_repeated(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_map(int argc, VALUE* argv, VALUE _self);
VALUE MessageBuilderContext_oneof(VALUE _self, VALUE name);
void OneofBuilderContext_mark(void* _self);
void OneofBuilderContext_free(void* _self);
VALUE OneofBuilderContext_alloc(VALUE klass);
void OneofBuilderContext_register(VALUE module);
OneofBuilderContext* ruby_to_OneofBuilderContext(VALUE value);
VALUE OneofBuilderContext_initialize(VALUE _self,
VALUE descriptor,
VALUE builder);
VALUE OneofBuilderContext_optional(int argc, VALUE* argv, VALUE _self);
void EnumBuilderContext_mark(void* _self);
void EnumBuilderContext_free(void* _self);
VALUE EnumBuilderContext_alloc(VALUE klass);
void EnumBuilderContext_register(VALUE module);
EnumBuilderContext* ruby_to_EnumBuilderContext(VALUE value);
VALUE EnumBuilderContext_initialize(VALUE _self, VALUE _file_builder,
VALUE name);
VALUE EnumBuilderContext_value(VALUE _self, VALUE name, VALUE number);
void FileBuilderContext_mark(void* _self);
void FileBuilderContext_free(void* _self);
VALUE FileBuilderContext_alloc(VALUE klass);
void FileBuilderContext_register(VALUE module);
FileBuilderContext* ruby_to_FileBuilderContext(VALUE _self);
upb_strview FileBuilderContext_strdup(VALUE _self, VALUE rb_str);
upb_strview FileBuilderContext_strdup_name(VALUE _self, VALUE rb_str);
upb_strview FileBuilderContext_strdup_sym(VALUE _self, VALUE rb_sym);
VALUE FileBuilderContext_initialize(VALUE _self, VALUE descriptor_pool,
VALUE name, VALUE options);
VALUE FileBuilderContext_add_message(VALUE _self, VALUE name);
VALUE FileBuilderContext_add_enum(VALUE _self, VALUE name);
VALUE FileBuilderContext_pending_descriptors(VALUE _self);
void Builder_mark(void* _self);
void Builder_free(void* _self);
VALUE Builder_alloc(VALUE klass);
void Builder_register(VALUE module);
Builder* ruby_to_Builder(VALUE value);
VALUE Builder_build(VALUE _self);
VALUE Builder_initialize(VALUE _self, VALUE descriptor_pool);
VALUE Builder_add_file(int argc, VALUE *argv, VALUE _self);
VALUE Builder_add_message(VALUE _self, VALUE name);
VALUE Builder_add_enum(VALUE _self, VALUE name);
VALUE Builder_finalize_to_pool(VALUE _self, VALUE pool_rb);
// -----------------------------------------------------------------------------
// Native slot storage abstraction.
// -----------------------------------------------------------------------------
#define NATIVE_SLOT_MAX_SIZE sizeof(uint64_t)
size_t native_slot_size(upb_fieldtype_t type);
void native_slot_set(const char* name,
upb_fieldtype_t type,
VALUE type_class,
void* memory,
VALUE value);
// Atomically (with respect to Ruby VM calls) either update the value and set a
// oneof case, or do neither. If |case_memory| is null, then no case value is
// set.
void native_slot_set_value_and_case(const char* name,
upb_fieldtype_t type,
VALUE type_class,
void* memory,
VALUE value,
uint32_t* case_memory,
uint32_t case_number);
VALUE native_slot_get(upb_fieldtype_t type,
VALUE type_class,
const void* memory);
void native_slot_init(upb_fieldtype_t type, void* memory);
void native_slot_mark(upb_fieldtype_t type, void* memory);
void native_slot_dup(upb_fieldtype_t type, void* to, void* from);
void native_slot_deep_copy(upb_fieldtype_t type, VALUE type_class, void* to,
void* from);
bool native_slot_eq(upb_fieldtype_t type, VALUE type_class, void* mem1,
void* mem2);
VALUE native_slot_encode_and_freeze_string(upb_fieldtype_t type, VALUE value);
void native_slot_check_int_range_precision(const char* name, upb_fieldtype_t type, VALUE value);
uint32_t slot_read_oneof_case(MessageLayout* layout, const void* storage,
const upb_oneofdef* oneof);
bool is_value_field(const upb_fielddef* f);
extern rb_encoding* kRubyStringUtf8Encoding;
extern rb_encoding* kRubyStringASCIIEncoding;
extern rb_encoding* kRubyString8bitEncoding;
VALUE field_type_class(const MessageLayout* layout, const upb_fielddef* field);
#define MAP_KEY_FIELD 1
#define MAP_VALUE_FIELD 2
// Oneof case slot value to indicate that no oneof case is set. The value `0` is
// safe because field numbers are used as case identifiers, and no field can
// have a number of 0.
#define ONEOF_CASE_NONE 0
// These operate on a map field (i.e., a repeated field of submessages whose
// submessage type is a map-entry msgdef).
bool is_map_field(const upb_fielddef* field);
const upb_fielddef* map_field_key(const upb_fielddef* field);
const upb_fielddef* map_field_value(const upb_fielddef* field);
// These operate on a map-entry msgdef.
const upb_fielddef* map_entry_key(const upb_msgdef* msgdef);
const upb_fielddef* map_entry_value(const upb_msgdef* msgdef);
// -----------------------------------------------------------------------------
// Repeated field container type.
// -----------------------------------------------------------------------------
typedef struct {
upb_fieldtype_t field_type;
VALUE field_type_class;
void* elements;
int size;
int capacity;
} RepeatedField;
void RepeatedField_mark(void* self);
void RepeatedField_free(void* self);
VALUE RepeatedField_alloc(VALUE klass);
VALUE RepeatedField_init(int argc, VALUE* argv, VALUE self);
void RepeatedField_register(VALUE module);
extern const rb_data_type_t RepeatedField_type;
extern VALUE cRepeatedField;
RepeatedField* ruby_to_RepeatedField(VALUE value);
VALUE RepeatedField_new_this_type(VALUE _self);
VALUE RepeatedField_each(VALUE _self);
VALUE RepeatedField_index(int argc, VALUE* argv, VALUE _self);
void* RepeatedField_index_native(VALUE _self, int index);
int RepeatedField_size(VALUE _self);
VALUE RepeatedField_index_set(VALUE _self, VALUE _index, VALUE val);
void RepeatedField_reserve(RepeatedField* self, int new_size);
VALUE RepeatedField_push(VALUE _self, VALUE val);
void RepeatedField_push_native(VALUE _self, void* data);
VALUE RepeatedField_pop_one(VALUE _self);
VALUE RepeatedField_insert(int argc, VALUE* argv, VALUE _self);
VALUE RepeatedField_replace(VALUE _self, VALUE list);
VALUE RepeatedField_clear(VALUE _self);
VALUE RepeatedField_length(VALUE _self);
VALUE RepeatedField_dup(VALUE _self);
VALUE RepeatedField_deep_copy(VALUE _self);
VALUE RepeatedField_to_ary(VALUE _self);
VALUE RepeatedField_eq(VALUE _self, VALUE _other);
VALUE RepeatedField_hash(VALUE _self);
VALUE RepeatedField_inspect(VALUE _self);
VALUE RepeatedField_plus(VALUE _self, VALUE list);
// Defined in repeated_field.c; also used by Map.
void validate_type_class(upb_fieldtype_t type, VALUE klass);
// -----------------------------------------------------------------------------
// Map container type.
// -----------------------------------------------------------------------------
typedef struct {
upb_fieldtype_t key_type;
upb_fieldtype_t value_type;
VALUE value_type_class;
VALUE parse_frame;
upb_strtable table;
} Map;
void Map_mark(void* self);
void Map_free(void* self);
VALUE Map_alloc(VALUE klass);
VALUE Map_init(int argc, VALUE* argv, VALUE self);
void Map_register(VALUE module);
VALUE Map_set_frame(VALUE self, VALUE val);
extern const rb_data_type_t Map_type;
extern VALUE cMap;
Map* ruby_to_Map(VALUE value);
VALUE Map_new_this_type(VALUE _self);
VALUE Map_each(VALUE _self);
VALUE Map_keys(VALUE _self);
VALUE Map_values(VALUE _self);
VALUE Map_index(VALUE _self, VALUE key);
VALUE Map_index_set(VALUE _self, VALUE key, VALUE value);
VALUE Map_has_key(VALUE _self, VALUE key);
VALUE Map_delete(VALUE _self, VALUE key);
VALUE Map_clear(VALUE _self);
VALUE Map_length(VALUE _self);
VALUE Map_dup(VALUE _self);
VALUE Map_deep_copy(VALUE _self);
VALUE Map_eq(VALUE _self, VALUE _other);
VALUE Map_hash(VALUE _self);
VALUE Map_to_h(VALUE _self);
VALUE Map_inspect(VALUE _self);
VALUE Map_merge(VALUE _self, VALUE hashmap);
VALUE Map_merge_into_self(VALUE _self, VALUE hashmap);
typedef struct {
Map* self;
upb_strtable_iter it;
} Map_iter;
void Map_begin(VALUE _self, Map_iter* iter);
void Map_next(Map_iter* iter);
bool Map_done(Map_iter* iter);
VALUE Map_iter_key(Map_iter* iter);
VALUE Map_iter_value(Map_iter* iter);
// -----------------------------------------------------------------------------
// Message layout / storage.
// -----------------------------------------------------------------------------
#define MESSAGE_FIELD_NO_HASBIT ((uint32_t)-1)
struct MessageField {
uint32_t offset;
uint32_t hasbit;
};
struct MessageOneof {
uint32_t offset;
uint32_t case_offset;
};
// MessageLayout is owned by the enclosing Descriptor, which must outlive us.
struct MessageLayout {
const Descriptor* desc;
const upb_msgdef* msgdef;
void* empty_template; // Can memcpy() onto a layout to clear it.
MessageField* fields;
MessageOneof* oneofs;
uint32_t size;
uint32_t value_offset;
int value_count;
int repeated_count;
int map_count;
};
#define ONEOF_CASE_MASK 0x80000000
void create_layout(Descriptor* desc);
void free_layout(MessageLayout* layout);
bool field_contains_hasbit(MessageLayout* layout,
const upb_fielddef* field);
VALUE layout_get_default(const upb_fielddef* field);
VALUE layout_get(MessageLayout* layout,
const void* storage,
const upb_fielddef* field);
void layout_set(MessageLayout* layout,
void* storage,
const upb_fielddef* field,
VALUE val);
VALUE layout_has(MessageLayout* layout,
const void* storage,
const upb_fielddef* field);
void layout_clear(MessageLayout* layout,
const void* storage,
const upb_fielddef* field);
void layout_init(MessageLayout* layout, void* storage);
void layout_mark(MessageLayout* layout, void* storage);
void layout_dup(MessageLayout* layout, void* to, void* from);
void layout_deep_copy(MessageLayout* layout, void* to, void* from);
VALUE layout_eq(MessageLayout* layout, void* msg1, void* msg2);
VALUE layout_hash(MessageLayout* layout, void* storage);
VALUE layout_inspect(MessageLayout* layout, void* storage);
bool is_wrapper_type_field(const upb_fielddef* field);
VALUE ruby_wrapper_type(VALUE type_class, VALUE value);
// -----------------------------------------------------------------------------
// Message class creation.
// -----------------------------------------------------------------------------
// This should probably be factored into a common upb component.
typedef struct {
upb_byteshandler handler;
upb_bytessink sink;
char *ptr;
size_t len, size;
} stringsink;
void stringsink_uninit(stringsink *sink);
struct MessageHeader {
Descriptor* descriptor; // kept alive by self.class.descriptor reference.
stringsink* unknown_fields; // store unknown fields in decoding.
// Data comes after this.
};
extern rb_data_type_t Message_type;
VALUE build_class_from_descriptor(VALUE descriptor);
void* Message_data(void* msg);
void Message_mark(void* self);
void Message_free(void* self);
VALUE Message_alloc(VALUE klass);
VALUE Message_method_missing(int argc, VALUE* argv, VALUE _self);
VALUE Message_initialize(int argc, VALUE* argv, VALUE _self);
VALUE Message_dup(VALUE _self);
VALUE Message_deep_copy(VALUE _self);
VALUE Message_eq(VALUE _self, VALUE _other);
VALUE Message_hash(VALUE _self);
VALUE Message_inspect(VALUE _self);
VALUE Message_to_h(VALUE _self);
VALUE Message_index(VALUE _self, VALUE field_name);
VALUE Message_index_set(VALUE _self, VALUE field_name, VALUE value);
VALUE Message_descriptor(VALUE klass);
VALUE Message_decode(VALUE klass, VALUE data);
VALUE Message_encode(VALUE klass, VALUE msg_rb);
VALUE Message_decode_json(int argc, VALUE* argv, VALUE klass);
VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass);
VALUE Google_Protobuf_discard_unknown(VALUE self, VALUE msg_rb);
VALUE Google_Protobuf_deep_copy(VALUE self, VALUE obj);
VALUE build_module_from_enumdesc(VALUE _enumdesc);
VALUE enum_lookup(VALUE self, VALUE number);
VALUE enum_resolve(VALUE self, VALUE sym);
VALUE enum_descriptor(VALUE self);
const upb_pbdecodermethod *new_fillmsg_decodermethod(
Descriptor* descriptor, const void *owner);
void add_handlers_for_message(const void *closure, upb_handlers *h);
// Maximum depth allowed during encoding, to avoid stack overflows due to
// cycles.
#define ENCODE_MAX_NESTING 63
// -----------------------------------------------------------------------------
// A cache of frozen string objects to use as field defaults.
// -----------------------------------------------------------------------------
VALUE get_frozen_string(const char* data, size_t size, bool binary);
// -----------------------------------------------------------------------------
// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
// instances.
// -----------------------------------------------------------------------------
VALUE get_msgdef_obj(VALUE descriptor_pool, const upb_msgdef* def);
VALUE get_enumdef_obj(VALUE descriptor_pool, const upb_enumdef* def);
VALUE get_fielddef_obj(VALUE descriptor_pool, const upb_fielddef* def);
VALUE get_filedef_obj(VALUE descriptor_pool, const upb_filedef* def);
VALUE get_oneofdef_obj(VALUE descriptor_pool, const upb_oneofdef* def);
// -----------------------------------------------------------------------------
// Utilities.
// -----------------------------------------------------------------------------
void check_upb_status(const upb_status* status, const char* msg);
#define CHECK_UPB(code, msg) do { \
upb_status status = UPB_STATUS_INIT; \
code; \
check_upb_status(&status, msg); \
} while (0)
extern ID descriptor_instancevar_interned;
// A distinct object that is not accessible from Ruby. We use this as a
// constructor argument to enforce that certain objects cannot be created from
// Ruby.
extern VALUE c_only_cookie;
#ifdef NDEBUG
#define UPB_ASSERT(expr) do {} while (false && (expr))
#else
#define UPB_ASSERT(expr) assert(expr)
#endif
#define UPB_UNUSED(var) (void)var
#endif // __GOOGLE_PROTOBUF_RUBY_PROTOBUF_H__
| 39.110945 | 96 | 0.698509 | [
"object"
] |
aec6a5f5457ec762b3869f74e320c89f8947fa4e | 2,464 | h | C | panda/src/egg/eggSwitchCondition.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2020-01-02T08:43:36.000Z | 2020-07-05T08:59:02.000Z | panda/src/egg/eggSwitchCondition.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/egg/eggSwitchCondition.h | ethanlindley/panda3d | 2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7 | [
"PHP-3.0",
"PHP-3.01"
] | 1 | 2020-03-11T17:38:45.000Z | 2020-03-11T17:38:45.000Z | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file eggSwitchCondition.h
* @author drose
* @date 1999-02-08
*/
#ifndef EGGSWITCHCONDITION
#define EGGSWITCHCONDITION
#include "pandabase.h"
#include "eggObject.h"
#include "luse.h"
/**
* This corresponds to a <SwitchCondition> entry within a group. It indicates
* the condition at which a level-of-detail is switched in or out. This is
* actually an abstract base class for potentially any number of specific
* different kinds of switching conditions; presently, only a <Distance> type
* is actually supported.
*/
class EXPCL_PANDAEGG EggSwitchCondition : public EggObject {
PUBLISHED:
virtual EggSwitchCondition *make_copy() const=0;
virtual void write(ostream &out, int indent_level) const=0;
virtual void transform(const LMatrix4d &mat)=0;
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
EggObject::init_type();
register_type(_type_handle, "EggSwitchCondition",
EggObject::get_class_type());
}
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
private:
static TypeHandle _type_handle;
};
/**
* A SwitchCondition that switches the levels-of-detail based on distance from
* the camera's eyepoint.
*/
class EXPCL_PANDAEGG EggSwitchConditionDistance : public EggSwitchCondition {
PUBLISHED:
EggSwitchConditionDistance(double switch_in, double switch_out,
const LPoint3d ¢er, double fade = 0.0);
virtual EggSwitchCondition *make_copy() const;
virtual void write(ostream &out, int indent_level) const;
virtual void transform(const LMatrix4d &mat);
public:
double _switch_in, _switch_out, _fade;
LPoint3d _center;
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
EggSwitchCondition::init_type();
register_type(_type_handle, "EggSwitchConditionDistance",
EggSwitchCondition::get_class_type());
}
virtual TypeHandle get_type() const {
return get_class_type();
}
private:
static TypeHandle _type_handle;
};
#endif
| 26.212766 | 78 | 0.726461 | [
"transform",
"3d"
] |
aec8395bd3af0991852631f8781f1ae6ea562387 | 2,096 | h | C | RecoLocalFastTime/FTLClusterizer/interface/MTDClusterParameterEstimator.h | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoLocalFastTime/FTLClusterizer/interface/MTDClusterParameterEstimator.h | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoLocalFastTime/FTLClusterizer/interface/MTDClusterParameterEstimator.h | bisnupriyasahu/cmssw | 6cf37ca459246525be0e8a6f5172c6123637d259 | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef RecoLocalFastTime_MTDCluster_Parameter_Estimator_H
#define RecoLocalFastTime_MTDCluster_Parameter_Estimator_H
#include "DataFormats/GeometrySurface/interface/LocalError.h"
#include "DataFormats/GeometryVector/interface/LocalPoint.h"
#include "Geometry/CommonDetUnit/interface/GeomDet.h"
#include "DataFormats/TrajectoryState/interface/LocalTrajectoryParameters.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
#include "DataFormats/FTLRecHit/interface/FTLCluster.h"
#include<tuple>
class MTDClusterParameterEstimator
{
public:
virtual ~MTDClusterParameterEstimator(){}
typedef std::pair<LocalPoint,LocalError> LocalValues;
typedef std::vector<LocalValues> VLocalValues;
typedef float TimeValue;
typedef float TimeValueError;
using ReturnType = std::tuple<LocalPoint,LocalError,TimeValue,TimeValueError>;
// here just to implement it in the clients;
// to be properly implemented in the sub-classes in order to make them thread-safe
virtual ReturnType getParameters(const FTLCluster & cl,
const GeomDetUnit & det) const =0;
virtual ReturnType getParameters(const FTLCluster & cl,
const GeomDetUnit & det,
const LocalTrajectoryParameters & ltp ) const =0;
virtual ReturnType getParameters(const FTLCluster & cl,
const GeomDetUnit & det,
const TrajectoryStateOnSurface& tsos ) const {
return getParameters(cl,det,tsos.localParameters());
}
virtual VLocalValues localParametersV(const FTLCluster& cluster, const GeomDetUnit& gd) const {
VLocalValues vlp;
ReturnType tuple = getParameters(cluster, gd);
vlp.emplace_back(std::get<0>(tuple), std::get<1>(tuple));
return vlp;
}
virtual VLocalValues localParametersV(const FTLCluster& cluster, const GeomDetUnit& gd, TrajectoryStateOnSurface& tsos) const {
VLocalValues vlp;
ReturnType tuple = getParameters(cluster, gd, tsos);
vlp.emplace_back(std::get<0>(tuple), std::get<1>(tuple));
return vlp;
}
MTDClusterParameterEstimator() {};
};
#endif
| 32.75 | 129 | 0.751908 | [
"geometry",
"vector"
] |
aeccd5033a556af6275fec8337b200d0a78e932b | 7,220 | h | C | components/network/ble/blemesh/src/foundation.h | 9names/bl_iot_sdk_autoformatted | 940b61a7f8177872763fb566a998d9c361e20699 | [
"Apache-2.0"
] | null | null | null | components/network/ble/blemesh/src/foundation.h | 9names/bl_iot_sdk_autoformatted | 940b61a7f8177872763fb566a998d9c361e20699 | [
"Apache-2.0"
] | null | null | null | components/network/ble/blemesh/src/foundation.h | 9names/bl_iot_sdk_autoformatted | 940b61a7f8177872763fb566a998d9c361e20699 | [
"Apache-2.0"
] | null | null | null | /* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __FOUNDATION_H__
#define __FOUNDATION_H__
#include "net/buf.h"
#define OP_APP_KEY_ADD BT_MESH_MODEL_OP_1(0x00)
#define OP_APP_KEY_UPDATE BT_MESH_MODEL_OP_1(0x01)
#define OP_DEV_COMP_DATA_STATUS BT_MESH_MODEL_OP_1(0x02)
#define OP_MOD_PUB_SET BT_MESH_MODEL_OP_1(0x03)
#define OP_HEALTH_CURRENT_STATUS BT_MESH_MODEL_OP_1(0x04)
#define OP_HEALTH_FAULT_STATUS BT_MESH_MODEL_OP_1(0x05)
#define OP_HEARTBEAT_PUB_STATUS BT_MESH_MODEL_OP_1(0x06)
#define OP_APP_KEY_DEL BT_MESH_MODEL_OP_2(0x80, 0x00)
#define OP_APP_KEY_GET BT_MESH_MODEL_OP_2(0x80, 0x01)
#define OP_APP_KEY_LIST BT_MESH_MODEL_OP_2(0x80, 0x02)
#define OP_APP_KEY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x03)
#define OP_ATTENTION_GET BT_MESH_MODEL_OP_2(0x80, 0x04)
#define OP_ATTENTION_SET BT_MESH_MODEL_OP_2(0x80, 0x05)
#define OP_ATTENTION_SET_UNREL BT_MESH_MODEL_OP_2(0x80, 0x06)
#define OP_ATTENTION_STATUS BT_MESH_MODEL_OP_2(0x80, 0x07)
#define OP_DEV_COMP_DATA_GET BT_MESH_MODEL_OP_2(0x80, 0x08)
#define OP_BEACON_GET BT_MESH_MODEL_OP_2(0x80, 0x09)
#define OP_BEACON_SET BT_MESH_MODEL_OP_2(0x80, 0x0a)
#define OP_BEACON_STATUS BT_MESH_MODEL_OP_2(0x80, 0x0b)
#define OP_DEFAULT_TTL_GET BT_MESH_MODEL_OP_2(0x80, 0x0c)
#define OP_DEFAULT_TTL_SET BT_MESH_MODEL_OP_2(0x80, 0x0d)
#define OP_DEFAULT_TTL_STATUS BT_MESH_MODEL_OP_2(0x80, 0x0e)
#define OP_FRIEND_GET BT_MESH_MODEL_OP_2(0x80, 0x0f)
#define OP_FRIEND_SET BT_MESH_MODEL_OP_2(0x80, 0x10)
#define OP_FRIEND_STATUS BT_MESH_MODEL_OP_2(0x80, 0x11)
#define OP_GATT_PROXY_GET BT_MESH_MODEL_OP_2(0x80, 0x12)
#define OP_GATT_PROXY_SET BT_MESH_MODEL_OP_2(0x80, 0x13)
#define OP_GATT_PROXY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x14)
#define OP_KRP_GET BT_MESH_MODEL_OP_2(0x80, 0x15)
#define OP_KRP_SET BT_MESH_MODEL_OP_2(0x80, 0x16)
#define OP_KRP_STATUS BT_MESH_MODEL_OP_2(0x80, 0x17)
#define OP_MOD_PUB_GET BT_MESH_MODEL_OP_2(0x80, 0x18)
#define OP_MOD_PUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x19)
#define OP_MOD_PUB_VA_SET BT_MESH_MODEL_OP_2(0x80, 0x1a)
#define OP_MOD_SUB_ADD BT_MESH_MODEL_OP_2(0x80, 0x1b)
#define OP_MOD_SUB_DEL BT_MESH_MODEL_OP_2(0x80, 0x1c)
#define OP_MOD_SUB_DEL_ALL BT_MESH_MODEL_OP_2(0x80, 0x1d)
#define OP_MOD_SUB_OVERWRITE BT_MESH_MODEL_OP_2(0x80, 0x1e)
#define OP_MOD_SUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x1f)
#define OP_MOD_SUB_VA_ADD BT_MESH_MODEL_OP_2(0x80, 0x20)
#define OP_MOD_SUB_VA_DEL BT_MESH_MODEL_OP_2(0x80, 0x21)
#define OP_MOD_SUB_VA_OVERWRITE BT_MESH_MODEL_OP_2(0x80, 0x22)
#define OP_NET_TRANSMIT_GET BT_MESH_MODEL_OP_2(0x80, 0x23)
#define OP_NET_TRANSMIT_SET BT_MESH_MODEL_OP_2(0x80, 0x24)
#define OP_NET_TRANSMIT_STATUS BT_MESH_MODEL_OP_2(0x80, 0x25)
#define OP_RELAY_GET BT_MESH_MODEL_OP_2(0x80, 0x26)
#define OP_RELAY_SET BT_MESH_MODEL_OP_2(0x80, 0x27)
#define OP_RELAY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x28)
#define OP_MOD_SUB_GET BT_MESH_MODEL_OP_2(0x80, 0x29)
#define OP_MOD_SUB_LIST BT_MESH_MODEL_OP_2(0x80, 0x2a)
#define OP_MOD_SUB_GET_VND BT_MESH_MODEL_OP_2(0x80, 0x2b)
#define OP_MOD_SUB_LIST_VND BT_MESH_MODEL_OP_2(0x80, 0x2c)
#define OP_LPN_TIMEOUT_GET BT_MESH_MODEL_OP_2(0x80, 0x2d)
#define OP_LPN_TIMEOUT_STATUS BT_MESH_MODEL_OP_2(0x80, 0x2e)
#define OP_HEALTH_FAULT_CLEAR BT_MESH_MODEL_OP_2(0x80, 0x2f)
#define OP_HEALTH_FAULT_CLEAR_UNREL BT_MESH_MODEL_OP_2(0x80, 0x30)
#define OP_HEALTH_FAULT_GET BT_MESH_MODEL_OP_2(0x80, 0x31)
#define OP_HEALTH_FAULT_TEST BT_MESH_MODEL_OP_2(0x80, 0x32)
#define OP_HEALTH_FAULT_TEST_UNREL BT_MESH_MODEL_OP_2(0x80, 0x33)
#define OP_HEALTH_PERIOD_GET BT_MESH_MODEL_OP_2(0x80, 0x34)
#define OP_HEALTH_PERIOD_SET BT_MESH_MODEL_OP_2(0x80, 0x35)
#define OP_HEALTH_PERIOD_SET_UNREL BT_MESH_MODEL_OP_2(0x80, 0x36)
#define OP_HEALTH_PERIOD_STATUS BT_MESH_MODEL_OP_2(0x80, 0x37)
#define OP_HEARTBEAT_PUB_GET BT_MESH_MODEL_OP_2(0x80, 0x38)
#define OP_HEARTBEAT_PUB_SET BT_MESH_MODEL_OP_2(0x80, 0x39)
#define OP_HEARTBEAT_SUB_GET BT_MESH_MODEL_OP_2(0x80, 0x3a)
#define OP_HEARTBEAT_SUB_SET BT_MESH_MODEL_OP_2(0x80, 0x3b)
#define OP_HEARTBEAT_SUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x3c)
#define OP_MOD_APP_BIND BT_MESH_MODEL_OP_2(0x80, 0x3d)
#define OP_MOD_APP_STATUS BT_MESH_MODEL_OP_2(0x80, 0x3e)
#define OP_MOD_APP_UNBIND BT_MESH_MODEL_OP_2(0x80, 0x3f)
#define OP_NET_KEY_ADD BT_MESH_MODEL_OP_2(0x80, 0x40)
#define OP_NET_KEY_DEL BT_MESH_MODEL_OP_2(0x80, 0x41)
#define OP_NET_KEY_GET BT_MESH_MODEL_OP_2(0x80, 0x42)
#define OP_NET_KEY_LIST BT_MESH_MODEL_OP_2(0x80, 0x43)
#define OP_NET_KEY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x44)
#define OP_NET_KEY_UPDATE BT_MESH_MODEL_OP_2(0x80, 0x45)
#define OP_NODE_IDENTITY_GET BT_MESH_MODEL_OP_2(0x80, 0x46)
#define OP_NODE_IDENTITY_SET BT_MESH_MODEL_OP_2(0x80, 0x47)
#define OP_NODE_IDENTITY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x48)
#define OP_NODE_RESET BT_MESH_MODEL_OP_2(0x80, 0x49)
#define OP_NODE_RESET_STATUS BT_MESH_MODEL_OP_2(0x80, 0x4a)
#define OP_SIG_MOD_APP_GET BT_MESH_MODEL_OP_2(0x80, 0x4b)
#define OP_SIG_MOD_APP_LIST BT_MESH_MODEL_OP_2(0x80, 0x4c)
#define OP_VND_MOD_APP_GET BT_MESH_MODEL_OP_2(0x80, 0x4d)
#define OP_VND_MOD_APP_LIST BT_MESH_MODEL_OP_2(0x80, 0x4e)
#define STATUS_SUCCESS 0x00
#define STATUS_INVALID_ADDRESS 0x01
#define STATUS_INVALID_MODEL 0x02
#define STATUS_INVALID_APPKEY 0x03
#define STATUS_INVALID_NETKEY 0x04
#define STATUS_INSUFF_RESOURCES 0x05
#define STATUS_IDX_ALREADY_STORED 0x06
#define STATUS_NVAL_PUB_PARAM 0x07
#define STATUS_NOT_SUB_MOD 0x08
#define STATUS_STORAGE_FAIL 0x09
#define STATUS_FEAT_NOT_SUPP 0x0a
#define STATUS_CANNOT_UPDATE 0x0b
#define STATUS_CANNOT_REMOVE 0x0c
#define STATUS_CANNOT_BIND 0x0d
#define STATUS_TEMP_STATE_CHG_FAIL 0x0e
#define STATUS_CANNOT_SET 0x0f
#define STATUS_UNSPECIFIED 0x10
#define STATUS_INVALID_BINDING 0x11
enum {
BT_MESH_VA_CHANGED, /* Label information changed */
};
struct label {
u16_t ref;
u16_t addr;
u8_t uuid[16];
atomic_t flags[1];
};
void bt_mesh_cfg_reset(void);
void bt_mesh_heartbeat(u16_t src, u16_t dst, u8_t hops, u16_t feat);
void bt_mesh_attention(struct bt_mesh_model *model, u8_t time);
struct label *get_label(u16_t index);
u8_t *bt_mesh_label_uuid_get(u16_t addr);
struct bt_mesh_hb_pub *bt_mesh_hb_pub_get(void);
void bt_mesh_hb_pub_disable(void);
struct bt_mesh_cfg_srv *bt_mesh_cfg_get(void);
u8_t bt_mesh_net_transmit_get(void);
u8_t bt_mesh_relay_get(void);
u8_t bt_mesh_friend_get(void);
u8_t bt_mesh_relay_retransmit_get(void);
u8_t bt_mesh_beacon_get(void);
u8_t bt_mesh_gatt_proxy_get(void);
u8_t bt_mesh_default_ttl_get(void);
void bt_mesh_subnet_del(struct bt_mesh_subnet *sub, bool store);
struct bt_mesh_app_key *bt_mesh_app_key_alloc(u16_t app_idx);
void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store);
#include <byteorder.h>
static inline void key_idx_pack(struct net_buf_simple *buf, u16_t idx1,
u16_t idx2) {
net_buf_simple_add_le16(buf, idx1 | ((idx2 & 0x00f) << 12));
net_buf_simple_add_u8(buf, idx2 >> 4);
}
static inline void key_idx_unpack(struct net_buf_simple *buf, u16_t *idx1,
u16_t *idx2) {
*idx1 = sys_get_le16(&buf->data[0]) & 0xfff;
*idx2 = sys_get_le16(&buf->data[1]) >> 4;
net_buf_simple_pull(buf, 3);
}
#endif /*__FOUNDATION_H__*/
| 41.734104 | 74 | 0.834488 | [
"mesh",
"model"
] |
aed089a13d9854783ef706725d094e7df65a5ba9 | 1,062 | h | C | libraries/model-baker/src/model-baker/CalculateTransformedExtentsTask.h | zontreck/hifi | c6cde9f0c9385b9df42dc6508688ae724b576555 | [
"Apache-2.0"
] | 14 | 2020-02-23T12:51:54.000Z | 2021-11-14T17:09:34.000Z | libraries/model-baker/src/model-baker/CalculateTransformedExtentsTask.h | zontreck/hifi | c6cde9f0c9385b9df42dc6508688ae724b576555 | [
"Apache-2.0"
] | 2 | 2018-11-01T02:16:43.000Z | 2018-11-16T00:45:44.000Z | libraries/model-baker/src/model-baker/CalculateTransformedExtentsTask.h | zontreck/hifi | c6cde9f0c9385b9df42dc6508688ae724b576555 | [
"Apache-2.0"
] | 5 | 2020-04-02T09:42:00.000Z | 2021-03-15T00:54:07.000Z | //
// CalculateTransformedExtentsTask.h
// model-baker/src/model-baker
//
// Created by Sabrina Shanman on 2019/10/04.
// Copyright 2019 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_CalculateExtentsTask_h
#define hifi_CalculateExtentsTask_h
#include "Engine.h"
#include "hfm/HFM.h"
// Calculates any undefined extents in the shapes and the model. Precalculated extents will be left alone.
// Bind extents will currently not be calculated
class CalculateTransformedExtentsTask {
public:
using Input = baker::VaryingSet4<Extents, std::vector<hfm::TriangleListMesh>, std::vector<hfm::Shape>, std::vector<hfm::Joint>>;
using Output = baker::VaryingSet2<Extents, std::vector<hfm::Shape>>;
using JobModel = baker::Job::ModelIO<CalculateTransformedExtentsTask, Input, Output>;
void run(const baker::BakeContextPointer& context, const Input& input, Output& output);
};
#endif // hifi_CalculateExtentsTask_h
| 35.4 | 132 | 0.756121 | [
"shape",
"vector",
"model"
] |
aed52eabda04989badf4fe7ca60425fdc6644f90 | 6,096 | h | C | frameworks/bridge/declarative_frontend/jsview/js_view.h | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/bridge/declarative_frontend/jsview/js_view.h | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/bridge/declarative_frontend/jsview/js_view.h | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:50.000Z | 2021-09-13T11:17:50.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_VIEW_H
#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_VIEW_H
#include <list>
#include "core/pipeline/base/composed_component.h"
#include "frameworks/bridge/declarative_frontend/engine/js_ref_ptr.h"
#include "frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h"
namespace OHOS::Ace {
class ComposedElement;
} // namespace OHOS::Ace
namespace OHOS::Ace::Framework {
class JSView;
class ViewFunctions : public AceType {
DECLARE_ACE_TYPE(ViewFunctions, AceType);
public:
ViewFunctions(JSRef<JSObject> jsObject, JSRef<JSFunc> jsRenderFunction);
~ViewFunctions()
{
LOGD("Destroy: ViewFunctions");
}
void Destroy(JSView* parentCustomView);
void ExecuteRender();
void ExecuteAppear();
void ExecuteDisappear();
void ExecuteAboutToBeDeleted();
void ExecuteAboutToRender();
void ExecuteOnRenderDone();
void ExecuteTransition();
bool ExecuteOnBackPress();
void ExecuteShow();
void ExecuteHide();
bool HasPageTransition() const;
void ExecuteFunction(JSWeak<JSFunc>& func, const char* debugInfo);
JSRef<JSVal> ExecuteFunctionWithReturn(JSWeak<JSFunc>& func, const char* debugInfo);
void SetContext(const JSExecutionContext& context)
{
context_ = context;
}
private:
JSWeak<JSVal> jsObject_;
JSWeak<JSFunc> jsAppearFunc_;
JSWeak<JSFunc> jsDisappearFunc_;
JSWeak<JSFunc> jsAboutToRenderFunc_;
JSWeak<JSFunc> jsAboutToBeDeletedFunc_;
JSWeak<JSFunc> jsRenderDoneFunc_;
JSWeak<JSFunc> jsAboutToBuildFunc_;
JSWeak<JSFunc> jsBuildDoneFunc_;
JSWeak<JSFunc> jsRenderFunc_;
JSWeak<JSFunc> jsTransitionFunc_;
JSWeak<JSVal> jsRenderResult_;
JSWeak<JSFunc> jsOnHideFunc_;
JSWeak<JSFunc> jsOnShowFunc_;
JSWeak<JSFunc> jsBackPressFunc_;
JSExecutionContext context_;
};
class JSView : public JSViewAbstract, public Referenced {
public:
JSView(const std::string& viewId, JSRef<JSObject> jsObject, JSRef<JSFunc> jsRenderFunction);
virtual ~JSView();
RefPtr<OHOS::Ace::Component> InternalRender();
void Destroy(JSView* parentCustomView);
RefPtr<Component> CreateComponent();
RefPtr<PageTransitionComponent> BuildPageTransitionComponent();
void MarkNeedUpdate();
bool NeedsUpdate()
{
return needsUpdate_;
}
/**
* Views which do not have a state can mark static.
* The element will be reused and re-render will be skipped.
*/
void MarkStatic()
{
isStatic_ = true;
}
bool IsStatic()
{
return isStatic_;
}
/**
* During render function execution, the child customview with same id will
* be recycled if they exist already in our child map. The ones which are not
* recycled needs to be cleaned. So After render function execution, clean the
* abandoned child customview.
*/
void CleanUpAbandonedChild();
/**
* Retries the customview child for recycling
* always use FindChildById to be certain before calling this method
*/
JSRefPtr<JSView> GetChildById(const std::string& viewId);
void FindChildById(const JSCallbackInfo& info);
void FireOnShow()
{
if (jsViewFunction_) {
jsViewFunction_->ExecuteShow();
}
}
void FireOnHide()
{
if (jsViewFunction_) {
jsViewFunction_->ExecuteHide();
}
}
bool FireOnBackPress()
{
if (jsViewFunction_) {
return jsViewFunction_->ExecuteOnBackPress();
}
return false;
}
void SetContext(const JSExecutionContext& context)
{
jsViewFunction_->SetContext(context);
}
/**
* New CustomView child will be added to the map.
* and it can be reterieved for recycling in next render function
* In next render call if this child is not recycled, it will be destroyed.
*/
void AddChildById(const std::string& viewId, const JSRefPtr<JSView>& obj);
void RemoveChildGroupById(const std::string& viewId);
static void Create(const JSCallbackInfo& info);
static void JSBind(BindingTarget globalObj);
static void ConstructorCallback(const JSCallbackInfo& args);
static void DestructorCallback(JSView* instance);
private:
WeakPtr<OHOS::Ace::ComposedElement> GetElement()
{
return element_;
}
void DestroyChild(JSView* parentCustomView);
/**
* Takes care of the viewId wrt to foreach
*/
std::string ProcessViewId(const std::string& viewId);
/**
* creates a set of valid viewids on a render function execution
* its cleared after cleaning up the abandoned child.
*/
void ChildAccessedById(const std::string& viewId);
// view id for custom view itself
std::string viewId_;
WeakPtr<OHOS::Ace::ComposedElement> element_ = nullptr;
bool needsUpdate_ = false;
bool isStatic_ = false;
RefPtr<ViewFunctions> jsViewFunction_;
// hold handle to the native and javascript object to keep them alive
// until they are abandoned
std::unordered_map<std::string, JSRefPtr<JSView>> customViewChildren_;
// a set of valid viewids on a renderfuntion excution
// its cleared after cleaning up the abandoned child.
std::unordered_set<std::string> lastAccessedViewIds_;
};
} // namespace OHOS::Ace::Framework
#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_VIEW_H
| 28.619718 | 96 | 0.700787 | [
"render",
"object"
] |
aedb6cb074c6c1f48329fd696a18575e47643d0a | 6,399 | h | C | src/common/type/stringList.h | toniczh/pgbackrest | d859fe8c4d60e961cf688f17fb80d0cdc8fb810d | [
"MIT"
] | 2 | 2019-11-13T02:25:38.000Z | 2021-10-30T03:00:10.000Z | src/common/type/stringList.h | fluca1978/pgbackrest | 3b9bed95186118a3fbf47e3e0900e74f4ad01217 | [
"MIT"
] | null | null | null | src/common/type/stringList.h | fluca1978/pgbackrest | 3b9bed95186118a3fbf47e3e0900e74f4ad01217 | [
"MIT"
] | null | null | null | /***********************************************************************************************************************************
String List Handler
***********************************************************************************************************************************/
#ifndef COMMON_TYPE_STRINGLIST_H
#define COMMON_TYPE_STRINGLIST_H
/***********************************************************************************************************************************
StringList object
***********************************************************************************************************************************/
typedef struct StringList StringList;
#include "common/memContext.h"
#include "common/type/list.h"
#include "common/type/string.h"
#include "common/type/variantList.h"
/***********************************************************************************************************************************
Constructors
***********************************************************************************************************************************/
// Create empty StringList
__attribute__((always_inline)) static inline StringList *
strLstNew(void)
{
return (StringList *)lstNewP(sizeof(String *), .comparator = lstComparatorStr);
}
// Split a string into a string list based on a delimiter
StringList *strLstNewSplitZ(const String *string, const char *delimiter);
__attribute__((always_inline)) static inline StringList *
strLstNewSplit(const String *string, const String *delimiter)
{
return strLstNewSplitZ(string, strZ(delimiter));
}
// New string list from a variant list -- all variants in the list must be type string
StringList *strLstNewVarLst(const VariantList *sourceList);
// Duplicate a string list
StringList *strLstDup(const StringList *sourceList);
/***********************************************************************************************************************************
Getters/Setters
***********************************************************************************************************************************/
// Set a new comparator
__attribute__((always_inline)) static inline StringList *
strLstComparatorSet(StringList *this, ListComparator *comparator)
{
return (StringList *)lstComparatorSet((List *)this, comparator);
}
// List size
__attribute__((always_inline)) static inline unsigned int
strLstSize(const StringList *this)
{
return lstSize((List *)this);
}
// Is the list empty?
__attribute__((always_inline)) static inline bool
strLstEmpty(const StringList *this)
{
return strLstSize(this) == 0;
}
/***********************************************************************************************************************************
Functions
***********************************************************************************************************************************/
// Add String to the list
String *strLstAdd(StringList *this, const String *string);
String *strLstAddZ(StringList *this, const char *string);
String *strLstAddIfMissing(StringList *this, const String *string);
// Does the specified string exist in the list?
__attribute__((always_inline)) static inline bool
strLstExists(const StringList *this, const String *string)
{
return lstExists((List *)this, &string);
}
// Insert into the list
String *strLstInsert(StringList *this, unsigned int listIdx, const String *string);
// Get a string by index
__attribute__((always_inline)) static inline String *
strLstGet(const StringList *this, unsigned int listIdx)
{
return *(String **)lstGet((List *)this, listIdx);
}
// Join a list of strings into a single string using the specified separator and quote with specified quote character
String *strLstJoinQuote(const StringList *this, const char *separator, const char *quote);
// Join a list of strings into a single string using the specified separator
__attribute__((always_inline)) static inline String *
strLstJoin(const StringList *this, const char *separator)
{
return strLstJoinQuote(this, separator, "");
}
// Return all items in this list which are not in the anti list. The input lists must *both* be sorted ascending or the results will
// be undefined.
StringList *strLstMergeAnti(const StringList *this, const StringList *anti);
// Move to a new parent mem context
__attribute__((always_inline)) static inline StringList *
strLstMove(StringList *this, MemContext *parentNew)
{
return (StringList *)lstMove((List *)this, parentNew);
}
// Return a null-terminated array of pointers to the zero-terminated strings in this list. DO NOT override const and modify any of
// the strings in this array, though it is OK to modify the array itself.
const char **strLstPtr(const StringList *this);
// Remove an item from the list
__attribute__((always_inline)) static inline bool
strLstRemove(StringList *this, const String *item)
{
return lstRemove((List *)this, &item);
}
__attribute__((always_inline)) static inline StringList *
strLstRemoveIdx(StringList *this, unsigned int listIdx)
{
return (StringList *)lstRemoveIdx((List *)this, listIdx);
}
// List sort
__attribute__((always_inline)) static inline StringList *
strLstSort(StringList *this, SortOrder sortOrder)
{
return (StringList *)lstSort((List *)this, sortOrder);
}
/***********************************************************************************************************************************
Destructor
***********************************************************************************************************************************/
__attribute__((always_inline)) static inline void
strLstFree(StringList *this)
{
lstFree((List *)this);
}
/***********************************************************************************************************************************
Macros for function logging
***********************************************************************************************************************************/
String *strLstToLog(const StringList *this);
#define FUNCTION_LOG_STRING_LIST_TYPE \
StringList *
#define FUNCTION_LOG_STRING_LIST_FORMAT(value, buffer, bufferSize) \
FUNCTION_LOG_STRING_OBJECT_FORMAT(value, strLstToLog, buffer, bufferSize)
#endif
| 41.019231 | 132 | 0.526801 | [
"object"
] |
aeea422569db5498436bbae58e1c43dd6cb1f2e9 | 6,789 | h | C | sample/exafmm-dev-13274dd4ac68/include/base_mpi.h | naoyam/tapas-reduce | 90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3 | [
"MIT"
] | null | null | null | sample/exafmm-dev-13274dd4ac68/include/base_mpi.h | naoyam/tapas-reduce | 90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3 | [
"MIT"
] | null | null | null | sample/exafmm-dev-13274dd4ac68/include/base_mpi.h | naoyam/tapas-reduce | 90ebf7eb6a2db232fc5ae0b4bff6b7ac3cf9b7d3 | [
"MIT"
] | null | null | null | #ifndef base_mpi_h
#define base_mpi_h
#include <mpi.h>
#include <iostream>
#include "types.h"
#include <unistd.h>
//! Custom MPI utilities
class BaseMPI {
private:
int external; //!< Flag to indicate external MPI_Init/Finalize
protected:
const int wait; //!< Waiting time between output of different ranks
public:
int mpirank; //!< Rank of MPI communicator
int mpisize; //!< Size of MPI communicator
public:
//! Constructor
BaseMPI() : external(0), wait(100) { // Initialize variables
int argc(0); // Dummy argument count
char **argv; // Dummy argument value
MPI_Initialized(&external); // Check if MPI_Init has been called
if (!external) MPI_Init(&argc, &argv); // Initialize MPI communicator
MPI_Comm_rank(MPI_COMM_WORLD, &mpirank); // Get rank of current MPI process
MPI_Comm_size(MPI_COMM_WORLD, &mpisize); // Get number of MPI processes
}
//! Destructor
~BaseMPI() {
if (!external) MPI_Finalize(); // Finalize MPI communicator
}
//! Allreduce int type from all ranks
int allreduceInt(int send) {
int recv; // Receive buffer
MPI_Allreduce(&send, &recv, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);// Communicate values
return recv; // Return received values
}
//! Allreduce vec3 type from all ranks
vec3 allreduceVec3(vec3 send) {
float fsend[3], frecv[3]; // Single precision buffers
for (int d=0; d<3; d++) fsend[d] = send[d]; // Copy to send buffer
MPI_Allreduce(fsend, frecv, 3, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);// Communicate values
vec3 recv; // Receive buffer
for (int d=0; d<3; d++) recv[d] = frecv[d]; // Copy from recv buffer
return recv; // Return received values
}
//! Allreduce bounds type from all ranks
Bounds allreduceBounds(Bounds local) {
float localXmin[3], localXmax[3], globalXmin[3], globalXmax[3];
for (int d=0; d<3; d++) { // Loop over dimensions
localXmin[d] = local.Xmin[d]; // Convert Xmin to float
localXmax[d] = local.Xmax[d]; // Convert Xmax to float
} // End loop over dimensions
MPI_Allreduce(localXmin, globalXmin, 3, MPI_FLOAT, MPI_MIN, MPI_COMM_WORLD);// Reduce domain Xmin
MPI_Allreduce(localXmax, globalXmax, 3, MPI_FLOAT, MPI_MAX, MPI_COMM_WORLD);// Reduce domain Xmax
Bounds global;
for (int d=0; d<3; d++) { // Loop over dimensions
real_t leeway = (globalXmax[d] - globalXmin[d]) * 1e-6; // Adding a bit of leeway to global domain
global.Xmin[d] = globalXmin[d] - leeway; // Convert Xmin to real_t
global.Xmax[d] = globalXmax[d] + leeway; // Convert Xmax to real_t
} // End loop over dimensions
return global; // Return global bounds
}
//! Print a scalar value on all ranks
template<typename T>
void print(T data) {
for (int irank=0; irank<mpisize; irank++ ) { // Loop over ranks
MPI_Barrier(MPI_COMM_WORLD); // Sync processes
usleep(wait); // Wait "wait" milliseconds
if (mpirank == irank) std::cout << data << " "; // If it's my turn print "data"
} // End loop over ranks
MPI_Barrier(MPI_COMM_WORLD); // Sync processes
usleep(wait); // Wait "wait" milliseconds
if (mpirank == mpisize-1) std::cout << std::endl; // New line
}
//! Print a scalar value on irank
template<typename T>
void print(T data, const int irank) {
MPI_Barrier(MPI_COMM_WORLD); // Sync processes
usleep(wait); // Wait "wait" milliseconds
if( mpirank == irank ) std::cout << data; // If it's my rank print "data"
}
//! Print a vector value on all ranks
template<typename T>
void print(T * data, const int begin, const int end) {
for (int irank=0; irank<mpisize; irank++) { // Loop over ranks
MPI_Barrier(MPI_COMM_WORLD); // Sync processes
usleep(wait); // Wait "wait" milliseconds
if (mpirank == irank) { // If it's my turn to print
std::cout << mpirank << " : "; // Print rank
for (int i=begin; i<end; i++) { // Loop over data
std::cout << data[i] << " "; // Print data[i]
} // End loop over data
std::cout << std::endl; // New line
} // Endif for my turn
} // End loop over ranks
}
//! Print a vector value on irank
template<typename T>
void print(T * data, const int begin, const int end, const int irank) {
MPI_Barrier(MPI_COMM_WORLD); // Sync processes
usleep(wait); // Wait "wait" milliseconds
if (mpirank == irank) { // If it's my rank
std::cout << mpirank << " : "; // Print rank
for (int i=begin; i<end; i++) { // Loop over data
std::cout << data[i] << " "; // Print data[i]
} // End loop over data
std::cout << std::endl; // New line
} // Endif for my rank
}
};
#endif
| 55.195122 | 115 | 0.441155 | [
"vector"
] |
aef099eb97d6da55d92551b183f2eaabc224b96a | 4,036 | h | C | Firmware-ESP/include/wisafe2_packets.h | Tho85/ws2mqtt | a29c53514917d9eff05eb06070b679676354bfa8 | [
"BSD-3-Clause"
] | 8 | 2022-03-12T22:37:40.000Z | 2022-03-21T21:08:10.000Z | Firmware-ESP/include/wisafe2_packets.h | Tho85/ws2mqtt | a29c53514917d9eff05eb06070b679676354bfa8 | [
"BSD-3-Clause"
] | null | null | null | Firmware-ESP/include/wisafe2_packets.h | Tho85/ws2mqtt | a29c53514917d9eff05eb06070b679676354bfa8 | [
"BSD-3-Clause"
] | null | null | null | #ifndef WISAFE_2_PACKETS_H
#define WISAFE_2_PACKETS_H 1
#pragma pack(push)
#pragma pack(1)
const uint8_t SPI_STOP_WORD = 0x7E;
const uint8_t DEVICE_TYPE_CO = 0x41;
const uint8_t DEVICE_TYPE_SMOKE = 0x81;
const uint8_t DEVICE_TYPE_ALL = 0xFF;
const uint16_t MODEL_WST630 = 0x0311;
const uint16_t MODEL_W2CO10X = 0x0378;
const uint16_t MODEL_FP1720W2R = 0x0411;
const uint16_t MODEL_ST630DE = 0x047C;
const uint16_t MODEL_W2SVP630 = 0x04C3;
const uint16_t MODEL_FP2620W2 = 0x08ED;
const uint8_t SPI_RX_REQUEST_WELCOME = 0x41;
const uint8_t SPI_RX_EVENT_ALARM = 0x50;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint8_t device_type;
uint8_t _unknown;
uint8_t sid;
uint8_t seq;
uint8_t stop;
} pkt_rx_event_alarm_t;
const uint8_t SPI_RX_EVENT_ALARM_OFF = 0x51;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint8_t device_type;
uint8_t sid;
uint8_t seq;
uint8_t stop;
} pkt_rx_event_alarm_off_t;
// Incoming test message
const uint8_t SPI_RX_EVENT_BUTTON = 0x70;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint8_t device_type;
uint8_t _unknown;
uint16_t model;
uint8_t sid;
uint8_t seq;
uint8_t stop;
} pkt_rx_event_button_t;
// Outgoing test message
const uint8_t SPI_TX_EVENT_BUTTON = 0x70;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint8_t device_type;
uint8_t _unknown;
uint16_t model;
uint8_t stop;
} pkt_tx_event_button_t;
const uint8_t SPI_RX_ERROR = 0x71;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint16_t model;
uint8_t error_flags;
uint8_t sid;
uint8_t seq;
uint8_t stop;
} pkt_rx_error_t;
const uint8_t SPI_RX_ERROR_FLAG_GENERIC = 0x02;
const uint8_t SPI_RX_ERROR_FLAG_DOCKED = 0x04;
const uint8_t SPI_RX_ERROR_FLAG_SENSOR_BATTERY = 0x08;
const uint8_t SPI_RX_ERROR_FLAG_RADIO_MODULE_BATTERY = 0x20;
const uint8_t SPI_TX_RESPONSE_WELCOME = 0x91;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint16_t model;
uint8_t device_type;
uint8_t flags;
uint16_t firmware;
uint8_t stop;
} pkt_tx_welcome_t;
// Response to D3 06 xx 01 7E
const uint8_t SPI_RX_DIAGNOSTIC_DETAILS_REMOTE_ID = 0xC4;
typedef struct {
uint8_t cmd;
uint32_t device_id:24;
uint8_t device_type;
uint16_t model;
uint8_t sid;
uint8_t seq;
uint8_t stop;
} pkt_rx_diagnostic_details_remote_id_t;
const uint8_t SPI_TX_DIAGNOSTIC_REQUEST = 0xD1;
const uint8_t SPI_RX_DIAGNOSTIC_RESPONSE = 0xD2;
typedef struct {
uint8_t cmd;
uint8_t battery1;
uint8_t battery2;
uint8_t _unknown1;
uint8_t rssi;
uint8_t firmware_version;
uint32_t device_id:24;
uint8_t flags;
uint8_t radio_fault_count;
uint8_t sid;
uint8_t _unknown2;
uint8_t stop;
} pkt_rx_diagnostic_response_t;
const uint8_t SPI_TX_DIAGNOSTIC_DETAILS_REQUEST = 0xD3;
typedef struct {
uint8_t cmd;
uint8_t subtype;
uint8_t stop;
} pkt_tx_diagnostic_details_t;
typedef struct {
uint8_t cmd;
uint8_t subtype;
uint8_t arg1;
uint8_t stop;
} pkt_tx_diagnostic_details_1arg_t;
typedef struct {
uint8_t cmd;
uint8_t subtype;
uint8_t arg1;
uint8_t arg2;
uint8_t stop;
} pkt_tx_diagnostic_details_2arg_t;
const uint8_t SPI_RX_DIAGNOSTIC_DETAILS_RESPONSE = 0xD4;
const uint8_t SPI_DIAGNOSTIC_DETAILS_UPDATE_SIDMAP = 0x03;
typedef struct {
uint8_t cmd;
uint8_t subtype_03;
uint64_t sidmap;
uint8_t stop;
} pkt_rx_diagnostic_details_update_sidmap_t;
const uint8_t SPI_DIAGNOSTIC_DETAILS_REMOTE_STATUS = 0x06;
const uint8_t SPI_TX_DIAGNOSTIC_DETAILS_STATUS = 0x00;
const uint8_t SPI_TX_DIAGNOSTIC_DETAILS_ID = 0x01;
// Response to D3 06 xx 00 7E
typedef struct {
uint8_t cmd;
uint8_t subtype_06;
uint8_t sid;
uint8_t battery1;
uint8_t battery2;
uint8_t _unknown1;
uint8_t rssi;
uint8_t firmware_version;
uint32_t device_id:24;
uint8_t flags;
uint8_t radio_fault_count;
uint8_t stop;
} pkt_rx_diagnostic_details_remote_status_t;
const uint8_t SPI_DIAGNOSTIC_DETAILS_NEW_DEVICE = 0x09;
typedef struct {
uint8_t cmd;
uint8_t subtype_09;
uint8_t sid;
uint32_t device_id:24;
uint8_t stop;
} pkt_rx_diagnostic_details_new_device_t;
#pragma pack(pop)
#endif
| 21.582888 | 60 | 0.801784 | [
"model"
] |
aef21985b5c28439b1a80993dd4ad91e7e995c06 | 13,552 | h | C | base/map-util.h | dendisuhubdy/gaia | a988b7f08a4080a3209eba6cb378718486947a68 | [
"BSD-2-Clause"
] | 72 | 2019-01-25T09:03:41.000Z | 2022-01-16T01:01:55.000Z | base/map-util.h | dendisuhubdy/gaia | a988b7f08a4080a3209eba6cb378718486947a68 | [
"BSD-2-Clause"
] | 35 | 2019-09-20T05:02:22.000Z | 2022-02-14T17:28:58.000Z | base/map-util.h | dendisuhubdy/gaia | a988b7f08a4080a3209eba6cb378718486947a68 | [
"BSD-2-Clause"
] | 15 | 2018-08-12T13:43:31.000Z | 2022-02-09T08:04:27.000Z | // Copyright 2005 Google Inc.
//
// #status: RECOMMENDED
// #category: maps
// #summary: Utility functions for use with map-like containers.
//
// This file provides utility functions for use with STL map-like data
// structures, such as std::map and hash_map. Some functions will also work with
// sets, such as ContainsKey().
//
// The main functions in this file fall into the following categories:
//
// - Find*()
// - Contains*()
// - Insert*()
// - Lookup*()
//
// These functions often have "...OrDie" or "...OrDieNoPrint" variants. These
// variants will crash the process with a CHECK() failure on error, including
// the offending key/data in the log message. The NoPrint variants will not
// include the key/data in the log output under the assumption that it's not a
// printable type.
//
// Most functions are fairly self explanatory from their names, with the
// exception of Find*() vs Lookup*(). The Find functions typically use the map's
// .find() member function to locate and return the map's value type. The
// Lookup*() functions typically use the map's .insert() (yes, insert) member
// function to insert the given value if necessary and returns (usually a
// reference to) the map's value type for the found item.
//
// See the per-function comments for specifics.
//
// There are also a handful of functions for doing other miscellaneous things.
//
// A note on terminology:
//
// Map-like containers are collections of pairs. Like all STL containers they
// contain a few standard typedefs identifying the types of data they contain.
// Given the following map declaration:
//
// map<string, int> my_map;
//
// the notable typedefs would be as follows:
//
// - key_type -- string
// - value_type -- pair<const string, int>
// - mapped_type -- int
//
// Note that the map above contains two types of "values": the key-value pairs
// themselves (value_type) and the values within the key-value pairs
// (mapped_type). A value_type consists of a key_type and a mapped_type.
//
// The documentation below is written for programmers thinking in terms of keys
// and the (mapped_type) values associated with a given key. For example, the
// statement
//
// my_map["foo"] = 3;
//
// has a key of "foo" (type: string) with a value of 3 (type: int).
//
#ifndef UTIL_GTL_MAP_UTIL_H_
#define UTIL_GTL_MAP_UTIL_H_
#include <stddef.h>
#include <utility>
#include <vector>
#include <type_traits>
#include "base/logging.h"
using std::pair;
//
// Find*()
//
// Returns a const reference to the value associated with the given key if it
// exists. Crashes otherwise.
//
// This is intended as a replacement for operator[] as an rvalue (for reading)
// when the key is guaranteed to exist.
//
// operator[] for lookup is discouraged for several reasons:
// * It has a side-effect of inserting missing keys
// * It is not thread-safe (even when it is not inserting, it can still
// choose to resize the underlying storage)
// * It invalidates iterators (when it chooses to resize)
// * It default constructs a value object even if it doesn't need to
//
// This version assumes the key is printable, and includes it in the fatal log
// message.
template <class Collection>
const typename Collection::value_type::second_type&
FindOrDie(const Collection& collection,
const typename Collection::value_type::first_type& key) {
typename Collection::const_iterator it = collection.find(key);
CHECK(it != collection.end()) << "Map key not found: " << key;
return it->second;
}
// Same as above, but returns a non-const reference.
template <class Collection>
typename Collection::value_type::second_type&
FindOrDie(Collection& collection, // NOLINT
const typename Collection::value_type::first_type& key) {
typename Collection::iterator it = collection.find(key);
CHECK(it != collection.end()) << "Map key not found: " << key;
return it->second;
}
// Returns a const reference to the value associated with the given key if it
// exists, otherwise a const reference to the provided default value is
// returned.
//
template <class Collection>
const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return value;
}
return it->second;
}
template <class Collection>
const typename Collection::value_type::second_type&
FindWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type&& value) = delete;
template <class Collection>
typename Collection::value_type::second_type
FindValueWithDefault(const Collection& collection,
const typename Collection::value_type::first_type& key,
typename Collection::value_type::second_type value) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return value;
}
return it->second;
}
// Returns a pointer to the const value associated with the given key if it
// exists, or NULL otherwise.
template <class Collection>
const typename Collection::value_type::second_type*
FindOrNull(const Collection& collection,
const typename Collection::value_type::first_type& key) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return 0;
}
return &it->second;
}
// Same as above but returns a pointer to the non-const value.
template <class Collection>
typename Collection::value_type::second_type*
FindOrNull(Collection& collection, // NOLINT
const typename Collection::value_type::first_type& key) {
typename Collection::iterator it = collection.find(key);
if (it == collection.end()) {
return 0;
}
return &it->second;
}
// Returns the pointer value associated with the given key. If none is found,
// NULL is returned. The function is designed to be used with a map of keys to
// pointers.
//
// This function does not distinguish between a missing key and a key mapped
// to a NULL value.
template <class Collection>
typename Collection::value_type::second_type
FindPtrOrNull(const Collection& collection,
const typename Collection::value_type::first_type& key) {
typename Collection::const_iterator it = collection.find(key);
if (it == collection.end()) {
return typename Collection::value_type::second_type(0);
}
return it->second;
}
// Given collection<Key,Value*>, tries to find key and if finds returns its value,
// otherwise allocates new value for that key and returns the new instance.
// second parameter is true if Key was found or false if the new allocation and insertion happened.
template <typename Collection> std::pair<typename Collection::value_type::second_type, bool>
FindPtrOrAllocate(
Collection* const collection,
const typename Collection::value_type::first_type& key) {
using Value = typename Collection::value_type::second_type;
static_assert(std::is_pointer<Value>::value, "must be pointer");
auto res = collection->emplace(key, nullptr);
if (res.second) {
res.first->second = new typename std::remove_pointer<Value>::type;
}
return std::pair<Value, bool>(res.first->second, !res.second);
}
// Same as above, except takes non-const reference to collection.
//
// This function is needed for containers that propagate constness to the
// pointee, such as boost::ptr_map.
template <class Collection>
typename Collection::value_type::second_type
FindPtrOrNull(Collection& collection, // NOLINT
const typename Collection::value_type::first_type& key) {
typename Collection::iterator it = collection.find(key);
if (it == collection.end()) {
return typename Collection::value_type::second_type(0);
}
return it->second;
}
//
// Contains*()
//
// Returns true iff the given collection contains the given key.
template <class Collection, class Key>
bool ContainsKey(const Collection& collection, const Key& key) {
typename Collection::const_iterator it = collection.find(key);
return it != collection.end();
}
// Returns true iff the given collection contains the given key-value pair.
template <class Collection, class Key, class Value>
bool ContainsKeyValuePair(const Collection& collection,
const Key& key,
const Value& value) {
typedef typename Collection::const_iterator const_iterator;
pair<const_iterator, const_iterator> range = collection.equal_range(key);
for (const_iterator it = range.first; it != range.second; ++it) {
if (it->second == value) {
return true;
}
}
return false;
}
//
// Insert*()
//
// Inserts the given key-value pair into the collection. Returns true if the
// given key didn't previously exist. If the given key already existed in the
// map, its value is changed to the given "value" and false is returned.
template <class Collection>
bool InsertOrUpdate(Collection* const collection,
const typename Collection::value_type& vt) {
pair<typename Collection::iterator, bool> ret = collection->insert(vt);
if (!ret.second) {
// update
ret.first->second = vt.second;
return false;
}
return true;
}
// Same as above, except that the key and value are passed separately.
template <class Collection>
bool InsertOrUpdate(Collection* const collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
return InsertOrUpdate(
collection, typename Collection::value_type(key, value));
}
// Inserts/updates all the key-value pairs from the range defined by the
// iterators "first" and "last" into the given collection.
template <class Collection, class InputIterator>
void InsertOrUpdateMany(Collection* const collection,
InputIterator first, InputIterator last) {
for (; first != last; ++first) {
InsertOrUpdate(collection, *first);
}
}
// Change the value associated with a particular key in a map or hash_map
// of the form map<Key, Value*> which owns the objects pointed to by the
// value pointers. If there was an existing value for the key, it is deleted.
// True indicates an insert took place, false indicates an update + delete.
template <class Collection>
bool InsertAndDeleteExisting(
Collection* const collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
pair<typename Collection::iterator, bool> ret =
collection->insert(typename Collection::value_type(key, value));
if (!ret.second) {
delete ret.first->second;
ret.first->second = value;
return false;
}
return true;
}
// Same as above except dies if the key already exists in the collection.
template <class Collection>
void InsertOrDie(Collection* const collection,
const typename Collection::value_type& value) {
CHECK(InsertIfNotPresent(collection, value)) << "duplicate value: " << value;
}
// Same as above except doesn't log the value on error.
template <class Collection>
void InsertOrDieNoPrint(Collection* const collection,
const typename Collection::value_type& value) {
CHECK(InsertIfNotPresent(collection, value)) << "duplicate value.";
}
// Inserts the key-value pair into the collection. Dies if key was already
// present.
template <class Collection>
void InsertOrDie(Collection* const collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& data) {
CHECK(InsertIfNotPresent(collection, key, data))
<< "duplicate key: " << key;
}
// Inserts a new key and default-initialized value. Dies if the key was already
// present. Returns a reference to the value. Example usage:
//
// map<int, SomeProto> m;
// SomeProto& proto = InsertKeyOrDie(&m, 3);
// proto.set_field("foo");
template <class Collection>
typename Collection::value_type::second_type& InsertKeyOrDie(
Collection* const collection,
const typename Collection::value_type::first_type& key) {
typedef typename Collection::value_type value_type;
pair<typename Collection::iterator, bool> res =
collection->insert(value_type(key, typename value_type::second_type()));
CHECK(res.second) << "duplicate key: " << key;
return res.first->second;
}
//
// Lookup*()
//
// Looks up a given key and value pair in a collection and inserts the key-value
// pair if it's not already present. Returns a reference to the value associated
// with the key.
template <class Collection>
typename Collection::value_type::second_type&
LookupOrInsert(Collection* const collection,
const typename Collection::value_type& vt) {
return collection->insert(vt).first->second;
}
// Same as above except the key-value are passed separately.
template <class Collection>
typename Collection::value_type::second_type&
LookupOrInsert(Collection* const collection,
const typename Collection::value_type::first_type& key,
const typename Collection::value_type::second_type& value) {
return LookupOrInsert(
collection, typename Collection::value_type(key, value));
}
#endif // UTIL_GTL_MAP_UTIL_H_
| 36.235294 | 99 | 0.717828 | [
"object",
"vector"
] |
089acb22bed1a37cf8c9efc6f4790917b63f04cd | 3,802 | h | C | Validation/GlobalHits/interface/GlobalHitsTester.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Validation/GlobalHits/interface/GlobalHitsTester.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | Validation/GlobalHits/interface/GlobalHitsTester.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef GlobalHitsTester_h
#define GlobalHitsTester_h
/** \class GlobalHitsAnalyzer
*
* Class to fill dqm monitor elements from existing EDM file
*
* \author M. Strang SUNY-Buffalo
*/
// framework & common header files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/Run.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "DataFormats/Provenance/interface/Provenance.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//#include "Geometry/CommonDetUnit/interface/GeomDet.h"
//#include "DataFormats/DetId/interface/DetId.h"
#include "TRandom.h"
#include "TRandom3.h"
//DQM services
#include "DQMServices/Core/interface/DQMEDAnalyzer.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DQMServices/Core/interface/MonitorElement.h"
// tracker info
//#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
//#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
//#include "DataFormats/SiStripDetId/interface/StripSubdetector.h"
//#include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h"
// muon info
//#include "Geometry/Records/interface/MuonGeometryRecord.h"
//#include "Geometry/CSCGeometry/interface/CSCGeometry.h"
//#include "Geometry/DTGeometry/interface/DTGeometry.h"
//#include "Geometry/RPCGeometry/interface/RPCGeometry.h"
//#include "DataFormats/MuonDetId/interface/MuonSubdetId.h"
//#include "DataFormats/MuonDetId/interface/RPCDetId.h"
//#include "DataFormats/MuonDetId/interface/DTWireId.h"
// calorimeter info
//#include "Geometry/Records/interface/IdealGeometryRecord.h"
//#include "Geometry/CaloGeometry/interface/CaloGeometry.h"
//#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
//#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
//#include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
//#include "DataFormats/HcalDetId/interface/HcalSubdetector.h"
// data in edm::event
//#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
//#include "SimDataFormats/Vertex/interface/SimVertexContainer.h"
//#include "SimDataFormats/Track/interface/SimTrackContainer.h"
//#include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h"
//#include "SimDataFormats/CaloHit/interface/PCaloHitContainer.h"
// helper files
//#include <CLHEP/Vector/LorentzVector.h>
//#include "DataFormats/Math/interface/LorentzVector.h"
//#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include <iostream>
#include <stdlib.h>
#include <string>
#include <memory>
#include <vector>
#include "TString.h"
class GlobalHitsTester : public DQMEDAnalyzer
{
public:
explicit GlobalHitsTester(const edm::ParameterSet&);
virtual ~GlobalHitsTester();
virtual void analyze(const edm::Event&, const edm::EventSetup&) override;
void bookHistograms(DQMStore::IBooker &,
edm::Run const &, edm::EventSetup const &) override;
private:
std::string fName;
int verbosity;
int frequency;
int vtxunit;
std::string label;
bool getAllProvenances;
bool printProvenanceInfo;
std::string outputfile;
bool doOutput;
MonitorElement *meTestString;
MonitorElement *meTestInt;
MonitorElement *meTestFloat;
MonitorElement *meTestTH1F;
MonitorElement *meTestTH2F;
MonitorElement *meTestTH3F;
MonitorElement *meTestProfile1;
MonitorElement *meTestProfile2;
TRandom *Random;
double RandomVal1;
double RandomVal2;
double RandomVal3;
// private statistics information
unsigned int count;
};
#endif
| 32.220339 | 75 | 0.79011 | [
"geometry",
"vector"
] |
089d8b7a287d839d02953e8cae2c80017a0547c7 | 17,659 | c | C | source/blender/draw/engines/eevee/eevee_renderpasses.c | aditiapratama/blender-compo-up | 105ed22b95859b8836d4d8541207440b5d5e1d49 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2020-08-07T11:35:09.000Z | 2021-07-21T01:55:42.000Z | source/blender/draw/engines/eevee/eevee_renderpasses.c | aditiapratama/blender-compo-up | 105ed22b95859b8836d4d8541207440b5d5e1d49 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/draw/engines/eevee/eevee_renderpasses.c | aditiapratama/blender-compo-up | 105ed22b95859b8836d4d8541207440b5d5e1d49 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 5 | 2020-08-03T13:03:29.000Z | 2021-08-07T22:10:26.000Z | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright 2019, Blender Foundation.
*/
/** \file
* \ingroup draw_engine
*/
#include "DRW_engine.h"
#include "DRW_render.h"
#include "draw_color_management.h" /* TODO remove dependency. */
#include "BKE_global.h" /* for G.debug_value */
#include "BLI_string_utils.h"
#include "DEG_depsgraph_query.h"
#include "eevee_private.h"
extern char datatoc_common_view_lib_glsl[];
extern char datatoc_common_uniforms_lib_glsl[];
extern char datatoc_bsdf_common_lib_glsl[];
extern char datatoc_renderpass_postprocess_frag_glsl[];
static struct {
struct GPUShader *postprocess_sh;
} e_data = {NULL}; /* Engine data */
typedef enum eRenderPassPostProcessType {
PASS_POST_UNDEFINED = 0,
PASS_POST_ACCUMULATED_COLOR = 1,
PASS_POST_ACCUMULATED_LIGHT = 2,
PASS_POST_ACCUMULATED_VALUE = 3,
PASS_POST_DEPTH = 4,
PASS_POST_AO = 5,
PASS_POST_NORMAL = 6,
PASS_POST_TWO_LIGHT_BUFFERS = 7,
} eRenderPassPostProcessType;
/* bitmask containing all renderpasses that need post-processing */
#define EEVEE_RENDERPASSES_WITH_POST_PROCESSING \
(EEVEE_RENDER_PASS_Z | EEVEE_RENDER_PASS_MIST | EEVEE_RENDER_PASS_NORMAL | \
EEVEE_RENDER_PASS_AO | EEVEE_RENDER_PASS_BLOOM | EEVEE_RENDER_PASS_VOLUME_SCATTER | \
EEVEE_RENDER_PASS_VOLUME_TRANSMITTANCE | EEVEE_RENDER_PASS_SHADOW | \
EEVEE_RENDERPASSES_MATERIAL)
#define EEVEE_RENDERPASSES_ALL \
(EEVEE_RENDERPASSES_WITH_POST_PROCESSING | EEVEE_RENDER_PASS_COMBINED)
#define EEVEE_RENDERPASSES_POST_PROCESS_ON_FIRST_SAMPLE \
(EEVEE_RENDER_PASS_Z | EEVEE_RENDER_PASS_NORMAL)
#define EEVEE_RENDERPASSES_COLOR_PASS \
(EEVEE_RENDER_PASS_DIFFUSE_COLOR | EEVEE_RENDER_PASS_SPECULAR_COLOR | EEVEE_RENDER_PASS_EMIT | \
EEVEE_RENDER_PASS_BLOOM)
#define EEVEE_RENDERPASSES_LIGHT_PASS \
(EEVEE_RENDER_PASS_DIFFUSE_LIGHT | EEVEE_RENDER_PASS_SPECULAR_LIGHT)
bool EEVEE_renderpasses_only_first_sample_pass_active(EEVEE_Data *vedata)
{
EEVEE_StorageList *stl = vedata->stl;
EEVEE_PrivateData *g_data = stl->g_data;
return (g_data->render_passes & ~EEVEE_RENDERPASSES_POST_PROCESS_ON_FIRST_SAMPLE) == 0;
}
void EEVEE_renderpasses_init(EEVEE_Data *vedata)
{
const DRWContextState *draw_ctx = DRW_context_state_get();
EEVEE_StorageList *stl = vedata->stl;
EEVEE_PrivateData *g_data = stl->g_data;
ViewLayer *view_layer = draw_ctx->view_layer;
View3D *v3d = draw_ctx->v3d;
if (v3d) {
const Scene *scene = draw_ctx->scene;
eViewLayerEEVEEPassType render_pass = v3d->shading.render_pass;
if (render_pass == EEVEE_RENDER_PASS_AO &&
((scene->eevee.flag & SCE_EEVEE_GTAO_ENABLED) == 0)) {
render_pass = EEVEE_RENDER_PASS_COMBINED;
}
else if (render_pass == EEVEE_RENDER_PASS_BLOOM &&
((scene->eevee.flag & SCE_EEVEE_BLOOM_ENABLED) == 0)) {
render_pass = EEVEE_RENDER_PASS_COMBINED;
}
g_data->render_passes = render_pass;
}
else {
eViewLayerEEVEEPassType enabled_render_passes = view_layer->eevee.render_passes;
#define ENABLE_FROM_LEGACY(name_legacy, name_eevee) \
SET_FLAG_FROM_TEST(enabled_render_passes, \
(view_layer->passflag & SCE_PASS_##name_legacy) != 0, \
EEVEE_RENDER_PASS_##name_eevee);
ENABLE_FROM_LEGACY(Z, Z)
ENABLE_FROM_LEGACY(MIST, MIST)
ENABLE_FROM_LEGACY(NORMAL, NORMAL)
ENABLE_FROM_LEGACY(SHADOW, SHADOW)
ENABLE_FROM_LEGACY(AO, AO)
ENABLE_FROM_LEGACY(EMIT, EMIT)
ENABLE_FROM_LEGACY(ENVIRONMENT, ENVIRONMENT)
ENABLE_FROM_LEGACY(DIFFUSE_COLOR, DIFFUSE_COLOR)
ENABLE_FROM_LEGACY(GLOSSY_COLOR, SPECULAR_COLOR)
ENABLE_FROM_LEGACY(DIFFUSE_DIRECT, DIFFUSE_LIGHT)
ENABLE_FROM_LEGACY(GLOSSY_DIRECT, SPECULAR_LIGHT)
ENABLE_FROM_LEGACY(ENVIRONMENT, ENVIRONMENT)
#undef ENABLE_FROM_LEGACY
g_data->render_passes = (enabled_render_passes & EEVEE_RENDERPASSES_ALL) |
EEVEE_RENDER_PASS_COMBINED;
}
EEVEE_material_renderpasses_init(vedata);
}
void EEVEE_renderpasses_output_init(EEVEE_ViewLayerData *sldata,
EEVEE_Data *vedata,
uint tot_samples)
{
EEVEE_FramebufferList *fbl = vedata->fbl;
EEVEE_TextureList *txl = vedata->txl;
EEVEE_StorageList *stl = vedata->stl;
EEVEE_EffectsInfo *effects = stl->effects;
EEVEE_PrivateData *g_data = stl->g_data;
const bool needs_post_processing = (g_data->render_passes &
EEVEE_RENDERPASSES_WITH_POST_PROCESSING) > 0;
if (needs_post_processing) {
/* Create FrameBuffer. */
/* Should be enough to store the data needs for a single pass.
* Some passes will use less, but it is only relevant for final renderings and
* when renderpasses other than `EEVEE_RENDER_PASS_COMBINED` are requested */
DRW_texture_ensure_fullscreen_2d(&txl->renderpass, GPU_RGBA16F, 0);
GPU_framebuffer_ensure_config(&fbl->renderpass_fb,
{GPU_ATTACHMENT_NONE, GPU_ATTACHMENT_TEXTURE(txl->renderpass)});
if ((g_data->render_passes & EEVEE_RENDERPASSES_MATERIAL) != 0) {
EEVEE_material_output_init(sldata, vedata, tot_samples);
}
if ((g_data->render_passes & EEVEE_RENDER_PASS_MIST) != 0) {
EEVEE_mist_output_init(sldata, vedata);
}
if ((g_data->render_passes & EEVEE_RENDER_PASS_SHADOW) != 0) {
EEVEE_shadow_output_init(sldata, vedata, tot_samples);
}
if ((g_data->render_passes & EEVEE_RENDER_PASS_AO) != 0) {
EEVEE_occlusion_output_init(sldata, vedata, tot_samples);
}
if ((g_data->render_passes & EEVEE_RENDER_PASS_BLOOM) != 0 &&
(effects->enabled_effects & EFFECT_BLOOM) != 0) {
EEVEE_bloom_output_init(sldata, vedata, tot_samples);
}
if ((g_data->render_passes &
(EEVEE_RENDER_PASS_VOLUME_TRANSMITTANCE | EEVEE_RENDER_PASS_VOLUME_SCATTER)) != 0) {
EEVEE_volumes_output_init(sldata, vedata, tot_samples);
}
/* We set a default texture as not all post processes uses the inputBuffer. */
g_data->renderpass_input = txl->color;
g_data->renderpass_col_input = txl->color;
g_data->renderpass_light_input = txl->color;
}
else {
/* Free unneeded memory */
DRW_TEXTURE_FREE_SAFE(txl->renderpass);
GPU_FRAMEBUFFER_FREE_SAFE(fbl->renderpass_fb);
}
}
void EEVEE_renderpasses_cache_finish(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
{
EEVEE_PassList *psl = vedata->psl;
EEVEE_PrivateData *g_data = vedata->stl->g_data;
DefaultTextureList *dtxl = DRW_viewport_texture_list_get();
const bool needs_post_processing = (g_data->render_passes &
EEVEE_RENDERPASSES_WITH_POST_PROCESSING) > 0;
if (needs_post_processing) {
if (e_data.postprocess_sh == NULL) {
DRWShaderLibrary *lib = EEVEE_shader_lib_get();
e_data.postprocess_sh = DRW_shader_create_fullscreen_with_shaderlib(
datatoc_renderpass_postprocess_frag_glsl, lib, NULL);
}
DRW_PASS_CREATE(psl->renderpass_pass, DRW_STATE_WRITE_COLOR);
DRWShadingGroup *grp = DRW_shgroup_create(e_data.postprocess_sh, psl->renderpass_pass);
DRW_shgroup_uniform_texture_ref(grp, "inputBuffer", &g_data->renderpass_input);
DRW_shgroup_uniform_texture_ref(grp, "inputColorBuffer", &g_data->renderpass_col_input);
DRW_shgroup_uniform_texture_ref(
grp, "inputSecondLightBuffer", &g_data->renderpass_light_input);
DRW_shgroup_uniform_texture_ref(grp, "depthBuffer", &dtxl->depth);
DRW_shgroup_uniform_block_ref(grp, "common_block", &sldata->common_ubo);
DRW_shgroup_uniform_block_ref(grp, "renderpass_block", &sldata->renderpass_ubo.combined);
DRW_shgroup_uniform_int(grp, "currentSample", &g_data->renderpass_current_sample, 1);
DRW_shgroup_uniform_int(grp, "renderpassType", &g_data->renderpass_type, 1);
DRW_shgroup_uniform_int(grp, "postProcessType", &g_data->renderpass_postprocess, 1);
DRW_shgroup_call(grp, DRW_cache_fullscreen_quad_get(), NULL);
}
else {
psl->renderpass_pass = NULL;
}
}
/* Post-process data to construct a specific render-pass
*
* This method will create a shading group to perform the post-processing for the given
* `renderpass_type`. The post-processing will be done and the result will be stored in the
* `vedata->txl->renderpass` texture.
*
* Only invoke this function for passes that need post-processing.
*
* After invoking this function the active frame-buffer is set to `vedata->fbl->renderpass_fb`. */
void EEVEE_renderpasses_postprocess(EEVEE_ViewLayerData *UNUSED(sldata),
EEVEE_Data *vedata,
eViewLayerEEVEEPassType renderpass_type)
{
EEVEE_PassList *psl = vedata->psl;
EEVEE_TextureList *txl = vedata->txl;
EEVEE_FramebufferList *fbl = vedata->fbl;
EEVEE_StorageList *stl = vedata->stl;
EEVEE_PrivateData *g_data = stl->g_data;
EEVEE_EffectsInfo *effects = stl->effects;
const int current_sample = effects->taa_current_sample;
g_data->renderpass_current_sample = current_sample;
g_data->renderpass_type = renderpass_type;
g_data->renderpass_postprocess = PASS_POST_UNDEFINED;
switch (renderpass_type) {
case EEVEE_RENDER_PASS_Z: {
g_data->renderpass_postprocess = PASS_POST_DEPTH;
break;
}
case EEVEE_RENDER_PASS_AO: {
g_data->renderpass_postprocess = PASS_POST_AO;
g_data->renderpass_input = txl->ao_accum;
break;
}
case EEVEE_RENDER_PASS_NORMAL: {
g_data->renderpass_postprocess = PASS_POST_NORMAL;
g_data->renderpass_input = effects->ssr_normal_input;
break;
}
case EEVEE_RENDER_PASS_MIST: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_VALUE;
g_data->renderpass_input = txl->mist_accum;
break;
}
case EEVEE_RENDER_PASS_VOLUME_SCATTER: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->volume_scatter_accum;
break;
}
case EEVEE_RENDER_PASS_VOLUME_TRANSMITTANCE: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->volume_transmittance_accum;
break;
}
case EEVEE_RENDER_PASS_SHADOW: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_VALUE;
g_data->renderpass_input = txl->shadow_accum;
break;
}
case EEVEE_RENDER_PASS_DIFFUSE_COLOR: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->diff_color_accum;
break;
}
case EEVEE_RENDER_PASS_SPECULAR_COLOR: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->spec_color_accum;
break;
}
case EEVEE_RENDER_PASS_ENVIRONMENT: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->env_accum;
break;
}
case EEVEE_RENDER_PASS_EMIT: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->emit_accum;
break;
}
case EEVEE_RENDER_PASS_SPECULAR_LIGHT: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_LIGHT;
g_data->renderpass_input = txl->spec_light_accum;
g_data->renderpass_col_input = txl->spec_color_accum;
if ((stl->effects->enabled_effects & EFFECT_SSR) != 0) {
g_data->renderpass_postprocess = PASS_POST_TWO_LIGHT_BUFFERS;
g_data->renderpass_light_input = txl->ssr_accum;
}
else {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_LIGHT;
}
break;
}
case EEVEE_RENDER_PASS_DIFFUSE_LIGHT: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_LIGHT;
g_data->renderpass_input = txl->diff_light_accum;
g_data->renderpass_col_input = txl->diff_color_accum;
if ((stl->effects->enabled_effects & EFFECT_SSS) != 0) {
g_data->renderpass_postprocess = PASS_POST_TWO_LIGHT_BUFFERS;
g_data->renderpass_light_input = txl->sss_accum;
}
else {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_LIGHT;
}
break;
}
case EEVEE_RENDER_PASS_BLOOM: {
g_data->renderpass_postprocess = PASS_POST_ACCUMULATED_COLOR;
g_data->renderpass_input = txl->bloom_accum;
g_data->renderpass_current_sample = 1;
break;
}
default: {
break;
}
}
GPU_framebuffer_bind(fbl->renderpass_fb);
DRW_draw_pass(psl->renderpass_pass);
}
void EEVEE_renderpasses_output_accumulate(EEVEE_ViewLayerData *sldata,
EEVEE_Data *vedata,
bool post_effect)
{
EEVEE_StorageList *stl = vedata->stl;
EEVEE_EffectsInfo *effects = stl->effects;
eViewLayerEEVEEPassType render_pass = stl->g_data->render_passes;
if (!post_effect) {
if ((render_pass & EEVEE_RENDER_PASS_MIST) != 0) {
EEVEE_mist_output_accumulate(sldata, vedata);
}
if ((render_pass & EEVEE_RENDER_PASS_AO) != 0) {
EEVEE_occlusion_output_accumulate(sldata, vedata);
}
if ((render_pass & EEVEE_RENDER_PASS_SHADOW) != 0) {
EEVEE_shadow_output_accumulate(sldata, vedata);
}
if ((render_pass & EEVEE_RENDERPASSES_MATERIAL) != 0) {
EEVEE_material_output_accumulate(sldata, vedata);
}
if ((render_pass &
(EEVEE_RENDER_PASS_VOLUME_TRANSMITTANCE | EEVEE_RENDER_PASS_VOLUME_SCATTER)) != 0) {
EEVEE_volumes_output_accumulate(sldata, vedata);
}
}
else {
if ((render_pass & EEVEE_RENDER_PASS_BLOOM) != 0 &&
(effects->enabled_effects & EFFECT_BLOOM) != 0) {
EEVEE_bloom_output_accumulate(sldata, vedata);
}
}
}
void EEVEE_renderpasses_draw(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
{
EEVEE_FramebufferList *fbl = vedata->fbl;
EEVEE_TextureList *txl = vedata->txl;
EEVEE_StorageList *stl = vedata->stl;
EEVEE_EffectsInfo *effects = stl->effects;
DefaultFramebufferList *dfbl = DRW_viewport_framebuffer_list_get();
/* We can only draw a single renderpass. Lightpasses also select their color pass (a second
pass). We mask the light pass when a light pass is selected. */
const eViewLayerEEVEEPassType render_pass =
((stl->g_data->render_passes & EEVEE_RENDERPASSES_LIGHT_PASS) != 0) ?
(stl->g_data->render_passes & EEVEE_RENDERPASSES_LIGHT_PASS) :
stl->g_data->render_passes;
const DRWContextState *draw_ctx = DRW_context_state_get();
const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
bool is_valid = (render_pass & EEVEE_RENDERPASSES_ALL) > 0;
bool needs_color_transfer = (render_pass & EEVEE_RENDERPASSES_COLOR_PASS) > 0 &&
DRW_state_is_opengl_render();
UNUSED_VARS(needs_color_transfer);
if ((render_pass & EEVEE_RENDER_PASS_BLOOM) != 0 &&
(effects->enabled_effects & EFFECT_BLOOM) == 0) {
is_valid = false;
}
/* When SSS isn't available, but the pass is requested, we mark it as invalid */
if ((render_pass & EEVEE_RENDER_PASS_AO) != 0 &&
(scene_eval->eevee.flag & SCE_EEVEE_GTAO_ENABLED) == 0) {
is_valid = false;
}
const int current_sample = stl->effects->taa_current_sample;
const int total_samples = stl->effects->taa_total_sample;
if ((render_pass & EEVEE_RENDERPASSES_POST_PROCESS_ON_FIRST_SAMPLE) &&
(current_sample > 1 && total_samples != 1)) {
return;
}
if (is_valid) {
EEVEE_renderpasses_postprocess(sldata, vedata, render_pass);
GPU_framebuffer_bind(dfbl->default_fb);
DRW_transform_none(txl->renderpass);
}
else {
/* Draw state is not valid for this pass, clear the buffer */
static float clear_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
GPU_framebuffer_bind(dfbl->default_fb);
GPU_framebuffer_clear_color(dfbl->default_fb, clear_color);
}
GPU_framebuffer_bind(fbl->main_fb);
}
void EEVEE_renderpasses_free(void)
{
DRW_SHADER_FREE_SAFE(e_data.postprocess_sh);
}
void EEVEE_renderpasses_draw_debug(EEVEE_Data *vedata)
{
EEVEE_TextureList *txl = vedata->txl;
EEVEE_StorageList *stl = vedata->stl;
EEVEE_EffectsInfo *effects = stl->effects;
GPUTexture *tx = NULL;
/* Debug : Output buffer to view. */
switch (G.debug_value) {
case 1:
tx = txl->maxzbuffer;
break;
case 2:
tx = effects->ssr_pdf_output;
break;
case 3:
tx = effects->ssr_normal_input;
break;
case 4:
tx = effects->ssr_specrough_input;
break;
case 5:
tx = txl->color_double_buffer;
break;
case 6:
tx = effects->gtao_horizons;
break;
case 7:
tx = effects->gtao_horizons;
break;
case 8:
tx = effects->sss_irradiance;
break;
case 9:
tx = effects->sss_radius;
break;
case 10:
tx = effects->sss_albedo;
break;
case 11:
tx = effects->velocity_tx;
break;
default:
break;
}
if (tx) {
DRW_transform_none(tx);
}
}
| 36.038776 | 98 | 0.715103 | [
"render"
] |
08a1cf3aea7ed5031f1e5a3e6bba4e6a8706fee7 | 556 | h | C | headers/statisticsinterface.h | decemyn/food-management | 8fc6619d15c70646540ba5b261e7c03b15f0d8e0 | [
"MIT"
] | null | null | null | headers/statisticsinterface.h | decemyn/food-management | 8fc6619d15c70646540ba5b261e7c03b15f0d8e0 | [
"MIT"
] | 2 | 2021-06-21T16:31:24.000Z | 2021-06-21T21:14:20.000Z | headers/statisticsinterface.h | decemyn/food-management | 8fc6619d15c70646540ba5b261e7c03b15f0d8e0 | [
"MIT"
] | null | null | null | #ifndef STATISTICSINTERFACE_H
#define STATISTICSINTERFACE_H
#include "headers/fileio.h"
#include "headers/product.h"
#include "headers/saleinterface.h"
#include <map>
#include <string>
#include <vector>
class StatisticsInterface {
private:
inline static const float ProfitMargin = 0.25;
public:
static std::vector<Product *> GetSoldProductsByDate(std::string);
static float GetProfitFromProductArray(std::vector<Product *>);
static std::string GetMostProfitableDay();
static Product *GetMostSoldProduct();
};
#endif // STATISTICSINTERFACE_H
| 23.166667 | 67 | 0.77518 | [
"vector"
] |
08a4304d66d5d09cead156cad941e3602b95a4a1 | 3,197 | c | C | d/antioch/ruins/mons/salamander.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/antioch/ruins/mons/salamander.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/antioch/ruins/mons/salamander.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#include "../ruins.h"
inherit MONSTER;
void create()
{
object ob;
::create();
set_name("salamander");
set_short("A fiery salamander");
set_id(({ "salamander", "fiery salamander", "monster", "fire snake" }));
set_long(
"%^RED%^The salamander is a fearesome sight indeed! Its lower half is" +
" that of a giant serpent, with sharp spines that stretch along" +
" his tail and back. The upper torso is that of a man..more or" +
" less. His underbelly is plated, and the plating extends up to" +
" his chest. His skin is more like the scales of a snake and is a" +
" bright %^ORANGE%^orange%^RED%^ and %^BOLD%^red%^RESET%^%^RED%^, mottled with %^BOLD%^%^BLACK%^black%^RESET%^%^RED%^ as though it is" +
" smoldering. Indeed, there seems to be heat coming off the" +
" creature! He has a flaming beard and moustache, with glowing" +
" yellow eyes. In his hand is a fiery spear that he obviously" +
" knows how to use."
);
set_gender("male");
set_body_type("humanoid");
set_race("salamander");
set_size(2);
add_limb("tail", "torso", 0, 0, 0);
remove_limb("right leg");
remove_limb("left leg");
remove_limb("right foot");
remove_limb("left foot");
set_alignment(9);
set("aggressive", 25);
set_max_level(30);
set_hd(20, 10);
set_level(20);
set_exp(3200);
set_class("fighter");
set_mlevel("fighter", 20);
set_property("full attacks", 1);
set_mob_magic_resistance("average");
set_property("weapon resistance", 2);
set_property("no hold", 1);
set_max_hp(180 + random(50));
set_hp(query_max_hp());
set_stats("strength", 20);
set_stats("charisma", 3);
set_stats("intelligence", 12);
set_stats("wisdom", 10);
set_stats("constitution", 18);
set_stats("dexterity", 14);
set_property("swarm", 1);
set_overall_ac(-15);
if (!random(6)) {
set_property("magic", 1);
}
new(OBJ + "fire_spear")->move(TO);
if (random(8)) {
present("fire spear", TO)->set_property("monsterweapon", 1);
}
command("wield fire spear");
set_diety("kossuth");
if (!random(2)) {
ob = new("/d/common/obj/brewing/herb_special_inherit");
ob->set_herb_name("tendril of flame");
ob->move(TO);
}
set_resistance("fire", 10);
set_resistance("cold", -15);
}
/* This was creating way too many gems over long reboots. Changing to produce on die. Circe 11/29/03
void reset()
{
::reset();
if(!random(3)) new("/d/antioch/valley/obj/gem.c")->move(TO);
if(!random(3)) new("/d/antioch/valley/obj/gem.c")->move(TO);
if(!random(3)) new("/d/antioch/valley/obj/gem.c")->move(TO);
}
*/
//it's meant to not have breaks to still offer chance of multiple gems. Circe 11/29/03
void die(mixed ob)
{
switch (random(4)) {
case 0: break;
case 1: new("/d/antioch/valley/obj/gem")->move(TO);
new("/d/antioch/valley/obj/gem")->move(TO);
case 2: new("/d/antioch/valley/obj/gem")->move(TO);
case 3: new("/d/antioch/valley/obj/gem")->move(TO);
break;
}
::die(ob);
}
| 32.292929 | 144 | 0.603065 | [
"object"
] |
08a76a46e373cf433665b7739b7776f61c7fdf31 | 2,270 | h | C | Python/tests/source_code_parser_test_files/MyFunctions.h | GervasioCalderon/bug-reproducer-assistant | a29aaa36b73292c14f3f0c83598c0d8991b0295a | [
"BSD-2-Clause"
] | 1 | 2022-03-21T18:41:31.000Z | 2022-03-21T18:41:31.000Z | Python/tests/source_code_parser_test_files/MyFunctions.h | GervasioCalderon/bug-reproducer-assistant | a29aaa36b73292c14f3f0c83598c0d8991b0295a | [
"BSD-2-Clause"
] | null | null | null | Python/tests/source_code_parser_test_files/MyFunctions.h | GervasioCalderon/bug-reproducer-assistant | a29aaa36b73292c14f3f0c83598c0d8991b0295a | [
"BSD-2-Clause"
] | null | null | null | //STL
#include <string>
#include <vector>
#include <map>
#include <iostream>
//Boost
#include <boost/lexical_cast.hpp>
using namespace std;
//Empty print for not disturbing the unit tests output
void myPrint(const string& str)
{
cout << str << endl;
}
int add(int i, int j)
{
return i + j;
}
int subtract(int i, int j)
{
return i - j;
}
void innerFunction()
{
}
void outerFunction()
{
innerFunction();
}
void noParamsFunction()
{
}
std::string mySubstring(const string& str, size_t length)
{
return str.substr(0, length);
}
void processVector( const vector< int >& aList )
{
myPrint("Entered processVector");
for ( vector< int >::const_iterator it = aList.begin(); it != aList.end(); ++it )
myPrint ("elem: " + boost::lexical_cast< string >(*it) + "\n");
}
void processIntMap( const map<int,int>& aMap )
{
myPrint("Entered processIntMap");
for ( map< int, int >::const_iterator it = aMap.begin(); it != aMap.end(); ++it )
{
myPrint ("key: " + boost::lexical_cast< string >(it->first) + "\n");
myPrint ("value: " + boost::lexical_cast< string >(it->second) + "\n");
}
}
struct MyClass
{
void f1()
{
myPrint( "No params" );
}
void f2(int i)
{
myPrint( "i:" + boost::lexical_cast< string > (i) );
}
void f3(const std::vector< int > aVector)
{
int x = aVector[0];
myPrint( "x:" + boost::lexical_cast< string >(x) );
}
void f4(std::map< std::string, int > aMap, MyClass * anObj)
{
int x = aMap["x"];
int y = aMap["y"];
myPrint("x: " + boost::lexical_cast< string >(x)+ ", y:" + boost::lexical_cast< string >(y) );
if ( anObj == NULL )
myPrint("anObj is NULL");
else
myPrint("anObj is not NULL");
}
};
class ClassWithConstructor
{
public:
ClassWithConstructor(int x, int y):
x_(x),
y_(y)
{
myPrint("No params");
}
int getX()
{
return x_;
}
void setX(int x)
{
x_ = x;
}
int getY()
{
return y_;
}
void setY(int y)
{
y_ = y;
}
private:
int x_;
int y_;
};
struct ClassWithStaticMethods
{
static void static0()
{
myPrint("static0");
}
static void static1( int x )
{
myPrint( "x:" + boost::lexical_cast< string >(x) );
}
}; | 16.449275 | 97 | 0.572687 | [
"vector"
] |
08aa2996e9a3cb2777592bb7a035ee8f0ed7d65d | 3,450 | h | C | include/cbag/polygon/transformation_util.h | bcanalog/cbag_polygon | 2c00d8c768fca40ced7905f77b4e3dad49c0b85b | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | include/cbag/polygon/transformation_util.h | bcanalog/cbag_polygon | 2c00d8c768fca40ced7905f77b4e3dad49c0b85b | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | include/cbag/polygon/transformation_util.h | bcanalog/cbag_polygon | 2c00d8c768fca40ced7905f77b4e3dad49c0b85b | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 Blue Cheetah Analog Design Inc.
// SPDX-License-Identifier: Apache-2.0
#ifndef CBAG_POLYGON_TRANSFORMATION_UTIL_H
#define CBAG_POLYGON_TRANSFORMATION_UTIL_H
#include <vector>
#include <cbag/polygon/enum.h>
#include <cbag/polygon/interval_data.h>
#include <cbag/polygon/point_data.h>
#include <cbag/polygon/polygon_concept.h>
#include <cbag/polygon/polygon_set_data.h>
#include <cbag/polygon/rectangle_concept.h>
#include <cbag/polygon/tag.h>
#include <cbag/polygon/transformation.h>
namespace cbag {
namespace polygon {
namespace dispatch {
template <typename T> T &transform(T &obj, const transformation<coord_type<T>> &xform, point_tag) {
using traits = get_traits_t<T>;
auto ans =
xform.transform(traits::get(obj, orientation_2d::X), traits::get(obj, orientation_2d::Y));
traits::set(obj, orientation_2d::X, ans[0]);
traits::set(obj, orientation_2d::Y, ans[1]);
return obj;
}
template <typename T>
T &transform(T &obj, const transformation<coord_type<T>> &xform, rectangle_tag) {
using unit = coord_type<T>;
if (is_valid(obj)) {
auto ll = point_ll(obj);
auto ur = point_ur(obj);
transform(ll, xform, point_tag{});
transform(ur, xform, point_tag{});
get_traits_t<T>::set(obj, orientation_2d::X,
interval_data<unit>{std::min(ur[0], ll[0]), std::max(ur[0], ll[0])});
get_traits_t<T>::set(obj, orientation_2d::Y,
interval_data<unit>{std::min(ur[1], ll[1]), std::max(ur[1], ll[1])});
}
return obj;
}
template <typename T>
T &transform(T &obj, const transformation<coord_type<T>> &xform, polygon_90_tag) {
auto n = size(obj);
auto iter = begin_points(obj);
auto coord_vec = std::vector<coord_type<T>>(n);
auto reverse = reverse_winding(xform.orient());
auto stop_idx = n - reverse * (n + 1);
auto inc = 1 - 2 * reverse;
for (std::size_t idx = reverse * (n - 1); idx != stop_idx; idx += inc, ++iter) {
auto tmp = *iter;
transform(tmp, xform, point_tag{});
coord_vec[idx] = get(tmp, static_cast<orientation_2d>(idx & 1));
}
get_traits_t<T>::set_compact(obj, std::move(coord_vec));
return obj;
}
template <typename T>
T &transform(T &obj, const transformation<coord_type<T>> &xform, polygon_tag) {
auto n = size(obj);
auto iter = begin_points(obj);
auto pt_vec = std::vector<std::remove_cv_t<std::remove_reference_t<decltype(*iter)>>>(n);
auto reverse = reverse_winding(xform.orient());
auto stop_idx = n - reverse * (n + 1);
auto inc = 1 - 2 * reverse;
for (std::size_t idx = reverse * (n - 1); idx != stop_idx; idx += inc, ++iter) {
pt_vec[idx] = *iter;
transform(pt_vec[idx], xform, point_tag{});
}
set_points(obj, std::move(pt_vec));
return obj;
}
} // namespace dispatch
template <typename T> T &transform(T &obj, const transformation<coord_type<T>> &xform) {
if (is_null(xform))
return obj;
return dispatch::transform(obj, xform, typename tag<T>::type{});
}
template <typename T> T get_transform(T obj, const transformation<coord_type<T>> &xform) {
dispatch::transform(obj, xform, typename tag<T>::type{});
return obj;
}
template <typename T>
polygon_set_data<T> &transform(polygon_set_data<T> &obj, const transformation<T> &xform) {
return obj.transform(xform);
}
} // namespace polygon
} // namespace cbag
#endif
| 32.242991 | 99 | 0.653043 | [
"vector",
"transform"
] |
08ac4742e200e4523cb5fe2e149a2b4a117fc9b8 | 9,952 | c | C | src-input/duk_heap_stringcache.c | ffontaine/duktape | 841b6fe9dc13f32954bc8c9d2fc4cc1a83ea5354 | [
"MIT"
] | null | null | null | src-input/duk_heap_stringcache.c | ffontaine/duktape | 841b6fe9dc13f32954bc8c9d2fc4cc1a83ea5354 | [
"MIT"
] | null | null | null | src-input/duk_heap_stringcache.c | ffontaine/duktape | 841b6fe9dc13f32954bc8c9d2fc4cc1a83ea5354 | [
"MIT"
] | null | null | null | /*
* String cache.
*
* Provides a cache to optimize indexed string lookups. The cache keeps
* track of (byte offset, char offset) states for a fixed number of strings.
* Otherwise we'd need to scan from either end of the string, as we store
* strings in (extended) UTF-8.
*/
#include "duk_internal.h"
/*
* Delete references to given hstring from the heap string cache.
*
* String cache references are 'weak': they are not counted towards
* reference counts, nor serve as roots for mark-and-sweep. When an
* object is about to be freed, such references need to be removed.
*/
DUK_INTERNAL void duk_heap_strcache_string_remove(duk_heap *heap, duk_hstring *h) {
duk_small_int_t i;
for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
duk_strcache *c = heap->strcache + i;
if (c->h == h) {
DUK_DD(DUK_DDPRINT("deleting weak strcache reference to hstring %p from heap %p",
(void *) h, (void *) heap));
c->h = NULL;
/* XXX: the string shouldn't appear twice, but we now loop to the
* end anyway; if fixed, add a looping assertion to ensure there
* is no duplicate.
*/
}
}
}
/*
* String scanning helpers
*
* All bytes other than UTF-8 continuation bytes ([0x80,0xbf]) are
* considered to contribute a character. This must match how string
* character length is computed.
*/
DUK_LOCAL const duk_uint8_t *duk__scan_forwards(const duk_uint8_t *p, const duk_uint8_t *q, duk_uint_fast32_t n) {
while (n > 0) {
for (;;) {
p++;
if (p >= q) {
return NULL;
}
if ((*p & 0xc0) != 0x80) {
break;
}
}
n--;
}
return p;
}
DUK_LOCAL const duk_uint8_t *duk__scan_backwards(const duk_uint8_t *p, const duk_uint8_t *q, duk_uint_fast32_t n) {
while (n > 0) {
for (;;) {
p--;
if (p < q) {
return NULL;
}
if ((*p & 0xc0) != 0x80) {
break;
}
}
n--;
}
return p;
}
/*
* Convert char offset to byte offset
*
* Avoid using the string cache if possible: for ASCII strings byte and
* char offsets are equal and for short strings direct scanning may be
* better than using the string cache (which may evict a more important
* entry).
*
* Typing now assumes 32-bit string byte/char offsets (duk_uint_fast32_t).
* Better typing might be to use duk_size_t.
*
* Caller should ensure 'char_offset' is within the string bounds [0,charlen]
* (endpoint is inclusive). If this is not the case, no memory unsafe
* behavior will happen but an error will be thrown.
*/
DUK_INTERNAL duk_uint_fast32_t duk_heap_strcache_offset_char2byte(duk_hthread *thr, duk_hstring *h, duk_uint_fast32_t char_offset) {
duk_heap *heap;
duk_strcache *sce;
duk_uint_fast32_t byte_offset;
duk_small_int_t i;
duk_bool_t use_cache;
duk_uint_fast32_t dist_start, dist_end, dist_sce;
duk_uint_fast32_t char_length;
const duk_uint8_t *p_start;
const duk_uint8_t *p_end;
const duk_uint8_t *p_found;
/*
* For ASCII strings, the answer is simple.
*/
if (DUK_LIKELY(DUK_HSTRING_IS_ASCII(h))) {
return char_offset;
}
char_length = (duk_uint_fast32_t) DUK_HSTRING_GET_CHARLEN(h);
DUK_ASSERT(char_offset <= char_length);
if (DUK_LIKELY(DUK_HSTRING_IS_ASCII(h))) {
/* Must recheck because the 'is ascii' flag may be set
* lazily. Alternatively, we could just compare charlen
* to bytelen.
*/
return char_offset;
}
/*
* For non-ASCII strings, we need to scan forwards or backwards
* from some starting point. The starting point may be the start
* or end of the string, or some cached midpoint in the string
* cache.
*
* For "short" strings we simply scan without checking or updating
* the cache. For longer strings we check and update the cache as
* necessary, inserting a new cache entry if none exists.
*/
DUK_DDD(DUK_DDDPRINT("non-ascii string %p, char_offset=%ld, clen=%ld, blen=%ld",
(void *) h, (long) char_offset,
(long) DUK_HSTRING_GET_CHARLEN(h),
(long) DUK_HSTRING_GET_BYTELEN(h)));
heap = thr->heap;
sce = NULL;
use_cache = (char_length > DUK_HEAP_STRINGCACHE_NOCACHE_LIMIT);
if (use_cache) {
#if defined(DUK_USE_DEBUG_LEVEL) && (DUK_USE_DEBUG_LEVEL >= 2)
DUK_DDD(DUK_DDDPRINT("stringcache before char2byte (using cache):"));
for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
duk_strcache *c = heap->strcache + i;
DUK_DDD(DUK_DDDPRINT(" [%ld] -> h=%p, cidx=%ld, bidx=%ld",
(long) i, (void *) c->h, (long) c->cidx, (long) c->bidx));
}
#endif
for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
duk_strcache *c = heap->strcache + i;
if (c->h == h) {
sce = c;
break;
}
}
}
/*
* Scan from shortest distance:
* - start of string
* - end of string
* - cache entry (if exists)
*/
DUK_ASSERT(DUK_HSTRING_GET_CHARLEN(h) >= char_offset);
dist_start = char_offset;
dist_end = char_length - char_offset;
dist_sce = 0; DUK_UNREF(dist_sce); /* initialize for debug prints, needed if sce==NULL */
p_start = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h);
p_end = (const duk_uint8_t *) (p_start + DUK_HSTRING_GET_BYTELEN(h));
p_found = NULL;
if (sce) {
if (char_offset >= sce->cidx) {
dist_sce = char_offset - sce->cidx;
if ((dist_sce <= dist_start) && (dist_sce <= dist_end)) {
DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
"dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
"scan forwards from sce",
(long) use_cache, (void *) (sce ? sce->h : NULL),
(sce ? (long) sce->cidx : (long) -1),
(sce ? (long) sce->bidx : (long) -1),
(long) dist_start, (long) dist_end, (long) dist_sce));
p_found = duk__scan_forwards(p_start + sce->bidx,
p_end,
dist_sce);
goto scan_done;
}
} else {
dist_sce = sce->cidx - char_offset;
if ((dist_sce <= dist_start) && (dist_sce <= dist_end)) {
DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
"dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
"scan backwards from sce",
(long) use_cache, (void *) (sce ? sce->h : NULL),
(sce ? (long) sce->cidx : (long) -1),
(sce ? (long) sce->bidx : (long) -1),
(long) dist_start, (long) dist_end, (long) dist_sce));
p_found = duk__scan_backwards(p_start + sce->bidx,
p_start,
dist_sce);
goto scan_done;
}
}
}
/* no sce, or sce scan not best */
if (dist_start <= dist_end) {
DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
"dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
"scan forwards from string start",
(long) use_cache, (void *) (sce ? sce->h : NULL),
(sce ? (long) sce->cidx : (long) -1),
(sce ? (long) sce->bidx : (long) -1),
(long) dist_start, (long) dist_end, (long) dist_sce));
p_found = duk__scan_forwards(p_start,
p_end,
dist_start);
} else {
DUK_DDD(DUK_DDDPRINT("non-ascii string, use_cache=%ld, sce=%p:%ld:%ld, "
"dist_start=%ld, dist_end=%ld, dist_sce=%ld => "
"scan backwards from string end",
(long) use_cache, (void *) (sce ? sce->h : NULL),
(sce ? (long) sce->cidx : (long) -1),
(sce ? (long) sce->bidx : (long) -1),
(long) dist_start, (long) dist_end, (long) dist_sce));
p_found = duk__scan_backwards(p_end,
p_start,
dist_end);
}
scan_done:
if (DUK_UNLIKELY(p_found == NULL)) {
/* Scan error: this shouldn't normally happen; it could happen if
* string is not valid UTF-8 data, and clen/blen are not consistent
* with the scanning algorithm.
*/
goto scan_error;
}
DUK_ASSERT(p_found >= p_start);
DUK_ASSERT(p_found <= p_end); /* may be equal */
byte_offset = (duk_uint32_t) (p_found - p_start);
DUK_DDD(DUK_DDDPRINT("-> string %p, cidx %ld -> bidx %ld",
(void *) h, (long) char_offset, (long) byte_offset));
/*
* Update cache entry (allocating if necessary), and move the
* cache entry to the first place (in an "LRU" policy).
*/
if (use_cache) {
/* update entry, allocating if necessary */
if (!sce) {
sce = heap->strcache + DUK_HEAP_STRCACHE_SIZE - 1; /* take last entry */
sce->h = h;
}
DUK_ASSERT(sce != NULL);
sce->bidx = (duk_uint32_t) (p_found - p_start);
sce->cidx = (duk_uint32_t) char_offset;
/* LRU: move our entry to first */
if (sce > &heap->strcache[0]) {
/*
* A C
* B A
* C <- sce ==> B
* D D
*/
duk_strcache tmp;
tmp = *sce;
duk_memmove((void *) (&heap->strcache[1]),
(const void *) (&heap->strcache[0]),
(size_t) (((char *) sce) - ((char *) &heap->strcache[0])));
heap->strcache[0] = tmp;
/* 'sce' points to the wrong entry here, but is no longer used */
}
#if defined(DUK_USE_DEBUG_LEVEL) && (DUK_USE_DEBUG_LEVEL >= 2)
DUK_DDD(DUK_DDDPRINT("stringcache after char2byte (using cache):"));
for (i = 0; i < DUK_HEAP_STRCACHE_SIZE; i++) {
duk_strcache *c = heap->strcache + i;
DUK_DDD(DUK_DDDPRINT(" [%ld] -> h=%p, cidx=%ld, bidx=%ld",
(long) i, (void *) c->h, (long) c->cidx, (long) c->bidx));
}
#endif
}
return byte_offset;
scan_error:
DUK_ERROR_INTERNAL(thr);
DUK_WO_NORETURN(return 0;);
}
| 32.103226 | 132 | 0.586415 | [
"object"
] |
08b233e699ca581a71455f4aed6474d4a5a6fb5f | 1,426 | h | C | Libraries/xcassets/Headers/xcassets/Asset/Group.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 2,077 | 2016-03-02T18:28:39.000Z | 2020-12-30T06:55:17.000Z | Libraries/xcassets/Headers/xcassets/Asset/Group.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 235 | 2016-03-02T18:05:40.000Z | 2020-12-22T09:31:01.000Z | Libraries/xcassets/Headers/xcassets/Asset/Group.h | njzhangyifei/xcbuild | f379277103ac2e457342b2b290ffa02d4293b74e | [
"BSD-2-Clause-NetBSD"
] | 183 | 2016-03-02T19:25:10.000Z | 2020-12-24T11:05:15.000Z | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
*/
#ifndef __xcassets_Asset_Group_h
#define __xcassets_Asset_Group_h
#include <xcassets/Asset/Asset.h>
#include <plist/Dictionary.h>
#include <memory>
#include <string>
#include <vector>
#include <ext/optional>
namespace xcassets {
namespace Asset {
class Group : public Asset {
private:
ext::optional<std::vector<std::string>> _onDemandResourceTags;
ext::optional<bool> _providesNamespace;
private:
friend class Asset;
using Asset::Asset;
public:
ext::optional<std::vector<std::string>> const &onDemandResourceTags() const
{ return _onDemandResourceTags; }
bool providesNamespace() const
{ return _providesNamespace.value_or(false); }
ext::optional<bool> providesNamespaceOptional() const
{ return _providesNamespace; }
public:
static AssetType Type()
{ return AssetType::Group; }
virtual AssetType type() const
{ return AssetType::Group; }
public:
/*
* Groups have no extension.
*/
static ext::optional<std::string> Extension()
{ return ext::nullopt; }
protected:
virtual bool parse(plist::Dictionary const *dict, std::unordered_set<std::string> *seen, bool check);
};
}
}
#endif // !__xcassets_Asset_Group_h
| 23 | 105 | 0.704769 | [
"vector"
] |
08b2a69d9d82847baa8d7cf3384dc73343a1330c | 2,430 | h | C | chrome/browser/sessions/persistent_tab_restore_service.h | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chrome/browser/sessions/persistent_tab_restore_service.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | chrome/browser/sessions/persistent_tab_restore_service.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SESSIONS_PERSISTENT_TAB_RESTORE_SERVICE_H_
#define CHROME_BROWSER_SESSIONS_PERSISTENT_TAB_RESTORE_SERVICE_H_
#include <vector>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/sessions/tab_restore_service.h"
#include "chrome/browser/sessions/tab_restore_service_helper.h"
class Profile;
// Tab restore service that persists data on disk.
class PersistentTabRestoreService : public TabRestoreService {
public:
// Does not take ownership of |time_factory|.
PersistentTabRestoreService(Profile* profile,
TimeFactory* time_factory);
virtual ~PersistentTabRestoreService();
// TabRestoreService:
virtual void AddObserver(TabRestoreServiceObserver* observer) OVERRIDE;
virtual void RemoveObserver(TabRestoreServiceObserver* observer) OVERRIDE;
virtual void CreateHistoricalTab(content::WebContents* contents,
int index) OVERRIDE;
virtual void BrowserClosing(TabRestoreServiceDelegate* delegate) OVERRIDE;
virtual void BrowserClosed(TabRestoreServiceDelegate* delegate) OVERRIDE;
virtual void ClearEntries() OVERRIDE;
virtual const Entries& entries() const OVERRIDE;
virtual std::vector<content::WebContents*> RestoreMostRecentEntry(
TabRestoreServiceDelegate* delegate,
chrome::HostDesktopType host_desktop_type) OVERRIDE;
virtual Tab* RemoveTabEntryById(SessionID::id_type id) OVERRIDE;
virtual std::vector<content::WebContents*> RestoreEntryById(
TabRestoreServiceDelegate* delegate,
SessionID::id_type id,
chrome::HostDesktopType host_desktop_type,
WindowOpenDisposition disposition) OVERRIDE;
virtual void LoadTabsFromLastSession() OVERRIDE;
virtual bool IsLoaded() const OVERRIDE;
virtual void DeleteLastSession() OVERRIDE;
virtual void Shutdown() OVERRIDE;
private:
friend class PersistentTabRestoreServiceTest;
class Delegate;
// Exposed for testing.
Entries* mutable_entries();
void PruneEntries();
scoped_ptr<Delegate> delegate_;
TabRestoreServiceHelper helper_;
DISALLOW_COPY_AND_ASSIGN(PersistentTabRestoreService);
};
#endif // CHROME_BROWSER_SESSIONS_PERSISTENT_TAB_RESTORE_SERVICE_H_
| 36.818182 | 76 | 0.782716 | [
"vector"
] |
08b718af21d9247cad995b46883fba0dd3d2360f | 3,710 | h | C | DataFormats/SiPixelCluster/interface/SiPixelClusterShapeCache.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | DataFormats/SiPixelCluster/interface/SiPixelClusterShapeCache.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | DataFormats/SiPixelCluster/interface/SiPixelClusterShapeCache.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | // -*- c++ -*-
#ifndef DataFormats_SiPixelCluster_SiPixelClusterShapeData_h
#define DataFormats_SiPixelCluster_SiPixelClusterShapeData_h
#include "DataFormats/Provenance/interface/ProductID.h"
#include "DataFormats/Common/interface/HandleBase.h"
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/DetSetVectorNew.h"
#include "DataFormats/SiPixelCluster/interface/SiPixelCluster.h"
#include <utility>
#include <vector>
#include <algorithm>
#include <cassert>
#include <memory>
class PixelGeomDetUnit;
class SiPixelClusterShapeData {
public:
typedef std::vector<std::pair<int, int> >::const_iterator const_iterator;
typedef std::pair<const_iterator, const_iterator> Range;
SiPixelClusterShapeData(const_iterator begin, const_iterator end, bool isStraight, bool isComplete, bool hasBigPixelsOnlyInside):
begin_(begin), end_(end), isStraight_(isStraight), isComplete_(isComplete), hasBigPixelsOnlyInside_(hasBigPixelsOnlyInside)
{}
~SiPixelClusterShapeData();
Range size() const { return std::make_pair(begin_, end_); }
bool isStraight() const { return isStraight_; }
bool isComplete() const { return isComplete_; }
bool hasBigPixelsOnlyInside() const { return hasBigPixelsOnlyInside_; }
private:
const_iterator begin_, end_;
const bool isStraight_, isComplete_, hasBigPixelsOnlyInside_;
};
class SiPixelClusterShapeCache {
public:
typedef edm::Ref<edmNew::DetSetVector<SiPixelCluster>, SiPixelCluster> ClusterRef;
struct Field {
Field(): offset(0), size(0), straight(false), complete(false), has(false), filled(false) {}
Field(unsigned off, unsigned siz, bool s, bool c, bool h):
offset(off), size(siz), straight(s), complete(c), has(h), filled(true) {}
unsigned offset: 24; // room for 2^24/9 = ~1.8e6 clusters, should be enough
unsigned size: 4; // max 9 elements / cluster (2^4-1=15)
unsigned straight:1;
unsigned complete:1;
unsigned has:1;
unsigned filled:1;
};
SiPixelClusterShapeCache() {};
explicit SiPixelClusterShapeCache(const edm::HandleBase& handle): productId_(handle.id()) {}
explicit SiPixelClusterShapeCache(const edm::ProductID& id): productId_(id) {}
~SiPixelClusterShapeCache();
void resize(size_t size) {
data_.resize(size);
sizeData_.reserve(size);
}
void swap(SiPixelClusterShapeCache& other) {
data_.swap(other.data_);
sizeData_.swap(other.sizeData_);
std::swap(productId_, other.productId_);
}
#if !defined(__CINT__) && !defined(__MAKECINT__) && !defined(__REFLEX__)
void shrink_to_fit() {
data_.shrink_to_fit();
sizeData_.shrink_to_fit();
}
template <typename T>
void insert(const ClusterRef& cluster, const T& data) {
static_assert(T::ArrayType::capacity() <= 15, "T::ArrayType::capacity() more than 15, bit field too narrow");
checkRef(cluster);
data_[cluster.index()] = Field(sizeData_.size(), data.size.size(), data.isStraight, data.isComplete, data.hasBigPixelsOnlyInside);
std::copy(data.size.begin(), data.size.end(), std::back_inserter(sizeData_));
}
bool isFilled(const ClusterRef& cluster) const {
checkRef(cluster);
return data_[cluster.index()].filled;
}
SiPixelClusterShapeData get(const ClusterRef& cluster, const PixelGeomDetUnit *pixDet) const {
checkRef(cluster);
Field f = data_[cluster.index()];
assert(f.filled);
auto beg = sizeData_.begin()+f.offset;
auto end = beg+f.size;
return SiPixelClusterShapeData(beg, end, f.straight, f.complete, f.has);
}
#endif
private:
void checkRef(const ClusterRef& cluster) const;
std::vector<Field> data_;
std::vector<std::pair<int, int> > sizeData_;
edm::ProductID productId_;
};
#endif
| 32.831858 | 134 | 0.731267 | [
"vector"
] |
08bc17ff71f8322a230c7eba26a9229694fb252a | 20,525 | c | C | src/blast_workqueue_backend.c | zhxu73/blast-workqueue | 373ced642a2072851ed09bd19346c345ec07f470 | [
"MIT"
] | null | null | null | src/blast_workqueue_backend.c | zhxu73/blast-workqueue | 373ced642a2072851ed09bd19346c345ec07f470 | [
"MIT"
] | 4 | 2019-10-29T23:43:28.000Z | 2019-10-29T23:50:25.000Z | src/blast_workqueue_backend.c | zhxu73/blast-workqueue | 373ced642a2072851ed09bd19346c345ec07f470 | [
"MIT"
] | null | null | null | /*
* Backend
*
* Receiving blast job from frontend via socket (unix or tcp), parse the job construct
* a WorkQueue task and dispatch to any connected worker for execution.
* After the the result come back, the result are stored in a file whose filename is
* specificed by the frontend.
* Message from frontend is in the format of "<cmd_file> <outfile>", which <cmd_file> is
* the filename of a file contains the blast command, and <outfile> is the filename that
* the frontend will be attempt to read for result.
*/
#include "work_queue.h"
#include "socket_comm.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <libgen.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define WQAPP_BACKEND_SOCKET_PATH "/var/www/sequenceserver/backend.server"
char *project_name = NULL;
char *password_file = NULL;
char *socket_path = NULL;
char *backend_ip = NULL;
int backend_port = -1;
int parse_cmd_arg(int argc, char *argv[]);
int start_recv_jobs(struct work_queue *q);
int handle_network_activity(int epfd, int listen_sock, struct work_queue *q);
int handle_new_conn(uint32_t events, int listen_sock, int epfd);
int handle_incoming_data(uint32_t events, int fd, struct work_queue *q);
int handle_msg(char *msg, struct work_queue *q, int conn_fd);
int parse_msg(const char *msg, char **local_infile, char **local_outfile, char **cmd);
char *parse_infile_from_cmd(const char *cmd, int *len);
int is_directory(const char *path);
int augument_cmd(char **cmd, char *local_infile, char *remote_outfile);
int create_task(struct work_queue *q, char *cmd_str, char *local_infile, char *local_outfile, int conn_fd);
int wait_result(struct work_queue *q);
void sigint_handler(int sig);
/*
* Main
*/
int main(int argc, char *argv[])
{
struct work_queue *q;
int port = WORK_QUEUE_DEFAULT_PORT;
int rc = 0;
rc = parse_cmd_arg(argc, argv);
if(rc != 0)
{
switch(rc)
{
case -1:
fprintf(stdout, "CMD ARG ERROR, need to give value when specify option\n");
break;
case -2:
fprintf(stdout, "CMD ARG ERROR, unix socket and tcp socket are mutal exclusive, use only one.\n\n");
break;
case -3:
fprintf(stdout, "CMD ARG ERROR, missing port or ip when using TCP socket.\n\n");
break;
case -4:
fprintf(stdout, "CMD ARG ERROR, invalid port number\n\n");
break;
}
fprintf(stdout, "Usage:\n");
fprintf(stdout, "listen on unix socket, %s, no password\n", WQAPP_BACKEND_SOCKET_PATH);
fprintf(stdout, "\t./blast_workqueue-backend\n");
fprintf(stdout, "listen on unix socket\n");
fprintf(stdout, "\t./blast_workqueue-backend --unix-sock <unix-sock-path>\n");
fprintf(stdout, "listen on tcp socket\n");
fprintf(stdout, "\t./blast_workqueue-backend --ip <ip> --port <port>\n");
fprintf(stdout, "\n\n");
fprintf(stdout, "Other Options:\n");
fprintf(stdout, "\t--password <pwd-filename>\n");
fprintf(stdout, "\t--project <project-name>\n");
exit(1);
}
if(signal(SIGINT, sigint_handler) == SIG_ERR)
{
fprintf(stderr, "Cannot catch SIGINT\n");
return -1;
}
// Create job queue
q = work_queue_create(port);
if(!q)
{
fprintf(stderr, "couldn't listen on port %d: %s\n", port, strerror(errno));
return -1;
}
fprintf(stdout, "WorkQueue listening on port %d...\n", work_queue_port(q));
// Specify password file if given
if(password_file != NULL)
{
rc = work_queue_specify_password_file(q, password_file);
if(!rc)
{
fprintf(stderr, "Cannot open the given password file, errno: %s\n", strerror(errno));
return -1;
}
fprintf(stdout, "Password file used...\n");
}
// Using project name, which means use catalog server
if(project_name != NULL)
{
work_queue_specify_name(q, project_name);
}
// Main Loop
rc = start_recv_jobs(q);
if(rc < 0) // when encounter fatal error, exit
{
work_queue_delete(q);
return -1;
}
return rc;
}
/*
* Parse command line argument
*
* @param argc
* @param argv
* @return 0 if success
* @return 1 if --help
* @return -1 if option has no value
* @return -2 if use unix & tcp sock together
* @return -3 if missing port or ip when using tcp
* @return -4 if invalid port
*/
int parse_cmd_arg(int argc, char *argv[])
{
if(argc == 1)
{
socket_path = WQAPP_BACKEND_SOCKET_PATH;
return 0;
}
for(int i = 1; i < argc; i++)
{
if(strcmp(argv[i], "--password") == 0)
{
if(i >= argc-1) return -1;
password_file = argv[i+1];
i++;
}
else if(strcmp(argv[i], "--unix-sock") == 0)
{
if(i >= argc-1) return -1;
if(backend_ip != NULL) return -2;
socket_path = argv[i+1];
i++;
}
else if(strcmp(argv[i], "--ip") == 0)
{
if(i >= argc-1) return -1;
if(socket_path != NULL) return -2;
backend_ip = argv[i+1];
i++;
}
else if(strcmp(argv[i], "--port") == 0)
{
if(i >= argc-1) return -1;
if(socket_path != NULL) return -2;
backend_port = atoi(argv[i+1]);
// Invalid port
if(backend_port == 0) return -4;
i++;
}
else if(strcmp(argv[i], "--project") == 0)
{
if(i >= argc-1) return -1;
project_name = argv[i+1];
i++;
}
else if(strcmp(argv[i], "--help") == 0)
{
return 1;
}
}
// Default value for unix socket path
if(socket_path == NULL && backend_ip == NULL && backend_port == -1)
{
socket_path = WQAPP_BACKEND_SOCKET_PATH;
}
// Missing port or missing ip when using TCP
if((backend_ip != NULL && backend_port == -1) || (backend_ip == NULL && backend_port != -1))
{
return -3;
}
return 0;
}
/*
* Main loop of this program.
* Listen on unix socket or tcp socket for frontend connection based on the cmd
* line option.
* Create a epoll instance for managing the network activity in a async fashion.
* Event-based processing of the epoll events.
*
* @param q A pointer to WorkQueue instance already created
* @return 0 if success, -1 if error
*/
int start_recv_jobs(struct work_queue *q)
{
int rc = 0;
// Create Socket
int listen_sock;
if(socket_path != NULL)
listen_sock = listening_unix_socket_init(socket_path);
else
listen_sock = listening_socket_init(backend_ip, backend_port);
if(listen_sock < 0)
{
return -1;
}
// Listen, and Create EPOLL
int epfd = listen_connection(listen_sock);
if(epfd < 0)
{
close(listen_sock);
return -1;
}
fprintf(stdout, "listening for frontend conn...\n");
while(1)
{
rc = handle_network_activity(epfd, listen_sock, q);
if(rc < 0) continue;
// Check for result & Send task to worker
rc = wait_result(q);
if(rc < 0) continue;
}
return rc;
}
/*
* Handle network activity with frontends
* Using epoll for notification on any new network activity, categorized the activity
* based on the fd.
* If the fd belongs to the listen_sock, then it means a new connection.
* Otherwise the connection means incoming data from connected frontend.
* Note: events could be error, e.g. EPOLLERR, in that case the event should be handled
* by the corrsponding function.
*
* @param epfd FD of epoll
* @param listen_sock FD of the listening socket, listening for frontend
* @param q A pointer to WorkQueue instance already created
* @return 0 if success, -1 if error
*/
int handle_network_activity(int epfd, int listen_sock, struct work_queue *q)
{
int rc = 0;
struct epoll_event events[5];
// check for epoll events
int nfds = epoll_wait(epfd, events, 5, 1);
for(int i = 0; i < nfds; i++)
{
// New Conn
if(events[i].data.fd == listen_sock)
{
rc = handle_new_conn(events[i].events, events[i].data.fd, epfd);
if(rc < 0) return rc;
}
// Incoming Data
else
{
rc = handle_incoming_data(events[i].events, events[i].data.fd, q);
if(rc < 0) return rc;
}
}
return rc;
}
/*
* Handle new connection from frontend.
* Once a new connection hit, accept the connection, and add the fd of the
* new connection to epoll.
*
* @param events events member of struct epoll_event, see man 2 epoll_ctl
* @param listen_sock FD of the socket listening for frontend connection
* @param epfd FD of epoll
* @return Return 0 if successful, return -1 if error
*/
int handle_new_conn(uint32_t events, int listen_sock, int epfd)
{
int rc;
if((events & EPOLLERR) || (events & EPOLLRDHUP) || (events & EPOLLRDHUP))
{
return -1;
}
int conn_sock = accept_connection(listen_sock);
if(conn_sock < 0) return 1;
rc = add_to_epoll(epfd, conn_sock);
if(rc < 0)
{
close(conn_sock);
return 1;
}
return 0;
}
/*
* Handle incoming data from frontend.
* If the event is not an error, read from the socket connection indicated by fd.
* Pass the read message to handler, if any.
* Connection will be closed after handling the message is finished, can be used
* as indication for result back for frontend.
*
* Note: msg is dynamically allocated, and this function is responsible for free it.
*
* @param events events member of struct epoll_event, see man 2 epoll_ctl
* @param fd FD of the frontend connection.
* @param q A pointer to WorkQueue instance already created
* @return Return 0 if successful, return -1 if error
*/
int handle_incoming_data(uint32_t events, int fd, struct work_queue *q)
{
if((events & EPOLLERR) || (events & EPOLLRDHUP) || (events & EPOLLRDHUP))
{
close(fd);
return -1;
}
int total_bytes = 0;
char *msg = read_from_sock(fd, &total_bytes);
if(msg != NULL)
{
if(total_bytes > 0 && handle_msg(msg, q, fd) < 0)
{
// Close Connection
close(fd);
}
free(msg);
}
else
{
// Close Connection
close(fd);
}
return 0;
}
/*
* Handle message from frontend.
* Call parse_msg() to parse the msg for filename of the local input file (query file),
* the filename of the local output file (files that the frontend will read for success
* output), and the blast command.
* And then calls augument_cmd() to augment the command to make it fit to execution
* on WorkQueue worker.
* Afterwards, create the task and submit it.
* Note: this function is responsible for free local_outfile, local_infile, cmd
*
* @param msg Message from frontend, needs to be null-terminated
* @param q A pointer to WorkQueue instance already created
* @param connfd FD of the connection to frontend
* @return Return 0 if successful, return -1 if error
*/
int handle_msg(char *msg, struct work_queue *q, int conn_fd)
{
int rc = 0;
fprintf(stdout, "msg: %s\n", msg);
char *local_outfile = NULL;
char *local_infile = NULL;
char *cmd = NULL;
rc = parse_msg(msg, &local_infile, &local_outfile, &cmd);
if(rc < 0)
{
fprintf(stderr, "Unable to parse msg\n");
return -1;
}
// Check if the infile is a directory
if(is_directory(local_infile))
{
fprintf(stderr, "Query file path is a directory\n");
free(local_infile);
free(local_outfile);
free(cmd);
return -1;
}
rc = augument_cmd(&cmd, local_infile, basename(local_outfile));
if(rc < 0)
{
fprintf(stderr, "Fail to augment command\n");
free(local_infile);
free(local_outfile);
free(cmd);
return -1;
}
fprintf(stdout, "creating task\n");
// Create and submit task
rc = create_task(q, cmd, local_infile, local_outfile, conn_fd);
free(local_infile);
free(local_outfile);
free(cmd);
return rc;
}
/*
* Parse the msg for filename of the local input file (query file), the filename
* of the local output file (files that the frontend will read for success output),
* and the blast command.
* msg is in the format of "<cmd_file> <outfile>".
* parse out the filename of the cmd file from msg, reads the blast command from it.
* call parse_infile_from_cmd() for parsing out input filename from the blast command.
* parse out the filename of the output file from msg.
*
* Note: local_file, local_outfile, cmd are allocated in this function, and needs to be
* freed by the caller after use.
*
* @param msg Message from frontend, needs to be null-terminted
* @param local_infile Output to caller of the filename of the local input file (query file)
* @param local_outfile Output to caller of the filename of the local output file
* @param cmd Output to caller of the raw blast command to be executed
* @return 0 if success, -1 if error
*/
int parse_msg(const char *msg, char **local_infile, char **local_outfile, char **cmd)
{
int rc = 0;
char *fst_space = strchr(msg, ' ');
if(fst_space == NULL) return -1;
// Parse out filename of outfile
char *outfile = fst_space+1;
*local_outfile = calloc(strlen(fst_space) + 10, sizeof(char));
strncpy(*local_outfile, outfile, strlen(fst_space));
// Read cmd
char cmd_file[fst_space - msg + 10];
strncpy(cmd_file, msg, fst_space - msg);
cmd_file[fst_space - msg] = '\0';
FILE *f = fopen(cmd_file, "r");
if(f == NULL)
{
fprintf(stderr, "Unable to open cmdfile\n");
free(*local_outfile);
return -1;
}
else
{
char *buffer = calloc(1024, sizeof(char));
int byte_read = fread(buffer, sizeof(char), 1024, f);
if(byte_read <= 0)
{
fprintf(stderr, "Unable to read anything from cmdfile, read %d bytes\n", byte_read);
free(*local_outfile);
free(buffer);
return -1;
}
*cmd = calloc(byte_read + 10, sizeof(char));
strncpy(*cmd, buffer, byte_read);
// Read out filename of input file
int infilename_len = 0;
char *infile = parse_infile_from_cmd(*cmd, &infilename_len);
if(infile == NULL)
{
free(*local_outfile);
free(buffer);
free(*cmd);
return -1;
}
*local_infile = calloc(infilename_len + 10, sizeof(char));
strncpy(*local_infile, infile, infilename_len);
(*local_infile)[infilename_len] = '\0';
free(buffer);
}
fclose(f);
return rc;
}
/*
* Parse the filename of the input/query file from the blast command.
* Assume the filename is barebone or in single quotes, and not double quotes
* and is either separate from "-query" by a '=' or ' '
* e.g.
* blast command:
* "blastn -db '/db/est_human /db/vector' -query '/var/www/12345.fa' -evalue 1e-5"
* filename of query file:
* "/var/www/12345.fa"
*
* @param cmd Blast command
* @param len Output to caller of the length of the filename
* @return A pointer that points to the 1st charater the filename starts(without single quotes)
*/
char *parse_infile_from_cmd(const char *cmd, int *len)
{
if(cmd == NULL || len == NULL) return NULL;
char *ptr = NULL;
*len = 0;
ptr = strstr(cmd, "-query");
if(ptr == NULL) return NULL;
char *start;
if((ptr[6] == ' ' || ptr[6] == '=') && ptr[7] != '\0')
start = ptr + 7;
else
return NULL;
char *end = strchr(start + 1, ' ');
if(end == NULL)
{
*len = strlen(cmd) - (start - cmd);
end = start + *len;
}
else
*len = end - start;
// if qfile is in single quote
if(*start == '\'' && *(end-1) == '\'')
{
start++;
*len -= 2;
}
return start;
}
/*
*
* @param path Path to be checked
* @return 1 if is dir, does exist, and has permission, 0 if not
*/
int is_directory(const char *path)
{
struct stat path_stat;
if (stat(path, &path_stat) == 0 && S_ISDIR(path_stat.st_mode))
return 1;
else
return 0;
}
/*
* Augument the blast command
* Swap/Replace the path (possibly absolute path) of query file inside the blast
* command with a relative path, since wq does not allow absolute path for remote.
* Add the output filename to at the end of the command.
* e.g.
* from:
* blastn -db '/db/est_human /db/vector' -query '/var/www/12345.fa' -evalue 1e-5
* to:
* blastn -db '/db/est_human /db/vector' -query '12345.fa' -evalue 1e-5 > blast-wq-XXXX.out
*
* Note: since the augumented cmd string might be longer than previous, reallocation
* could occur, hence reqiure char**, and the address of the pointer might change
*
* @param cmd Input/Output from/to caller, blast command
* @param local_infile Local filename of the query file (possibly absolute)
* @param remote_outfile Remote filename of the query file, relative path
* @return 0 if success, -1 if error
*/
int augument_cmd(char **cmd, char *local_infile, char *remote_outfile)
{
int alloc_len = strlen(*cmd) + strlen(remote_outfile) + 20;
char *ptr1 = strstr(*cmd, local_infile);
if(ptr1 == NULL) return -1;
char *ptr2 = strstr(*cmd, basename(local_infile));
if(ptr2 == NULL) return -1;
while(*ptr2 != '\0')
{
*ptr1 = *ptr2;
ptr1++;
ptr2++;
}
*ptr1 = '\0';
char *new_alloc = realloc(*cmd, sizeof(char) * alloc_len);
if(new_alloc == NULL)
return -1;
*cmd = new_alloc;
snprintf(*cmd + strlen(*cmd), alloc_len, " > %s", remote_outfile);
return 0;
}
/*
* Create a WorkQueue task and submit to the wq queue for later dispatch.
* Remote path of query/Input file and output file are generated using basename() function.
*
* @param q A pointer to WorkQueue instance already created
* @param cmd_str Augumented blast command
* @param local_infile local filename of the query file
* @param local_outfile local filename of the output file
* @param conn_fd FD for the connection to frontend
* @return 0 if success, -1 if error
*/
int create_task(struct work_queue *q, char *cmd_str, char *local_infile, char *local_outfile, int conn_fd)
{
struct work_queue_task *t;
// Create task off the cmd
t = work_queue_task_create(cmd_str);
if(t == NULL) return -1;
// Use the conn_fd as tag
char tag[15];
sprintf(tag, "%d", conn_fd);
work_queue_task_specify_tag(t, tag);
// Specify input & output files
work_queue_task_specify_file(t, local_infile, basename(local_infile), WORK_QUEUE_INPUT, WORK_QUEUE_NOCACHE);
work_queue_task_specify_file(t, local_outfile, basename(local_outfile), WORK_QUEUE_OUTPUT, WORK_QUEUE_NOCACHE);
// Submit task
int taskid = work_queue_submit(q, t);
printf("submitted task (id# %d): %s\n", taskid, t->command_line);
return 0;
}
/*
* Wait for any result returned from WorkQueue worker, and sends task to worker.
* currently no retry after failure.
*
* @param q A pointer to WorkQueue instance already created
* @return 0 if success, -1 if error
*/
int wait_result(struct work_queue *q)
{
// Check if result of any task returns, and send task to workers
struct work_queue_task *t = work_queue_wait(q, 0);
// If a task returns
if(t)
{
printf("task (id# %d) complete: %s (return code %d)\n", t->taskid, t->command_line, t->return_status);
// Obtain the FD of the connection from tag
int conn_fd = atoi(t->tag);
close(conn_fd);
if(t->return_status != 0)
{
// The task failed. Error handling (e.g., resubmit with new parameters) here.
}
work_queue_task_delete(t);
}
return 0;
}
/*
* Signal handler, so that the program can exit gracefully after clean up.
*
* @param sig Type of signal received, this value is ignored, since this only handles SIGINT
*/
void sigint_handler(int sig)
{
fprintf(stdout, "SIGINT, clean up\n");
exit(0);
}
| 29.532374 | 116 | 0.620804 | [
"vector"
] |
08bcae5f1f09716293d52fe442fb3a194e474c56 | 4,894 | h | C | ReClass/NativeObjects.h | KN4CK3R/Reclass-2016 | ace933511eb2f0cc639101c05e9e601a4392f7f6 | [
"MIT"
] | 5 | 2017-07-24T19:52:51.000Z | 2021-02-17T20:24:55.000Z | ReClass/NativeObjects.h | Brattlof/Reclass-2016 | ace933511eb2f0cc639101c05e9e601a4392f7f6 | [
"MIT"
] | null | null | null | ReClass/NativeObjects.h | Brattlof/Reclass-2016 | ace933511eb2f0cc639101c05e9e601a4392f7f6 | [
"MIT"
] | 4 | 2016-11-18T23:04:26.000Z | 2020-06-12T05:38:17.000Z | #pragma once
#include "NativeCommon.h"
///
/// < Objects Macros and Definitions >
///
#define OBJECT_TYPE_CREATE 0x0001
#define OBJECT_TYPE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)
#define DIRECTORY_QUERY 0x0001
#define DIRECTORY_TRAVERSE 0x0002
#define DIRECTORY_CREATE_OBJECT 0x0004
#define DIRECTORY_CREATE_SUBDIRECTORY 0x0008
#define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0xF)
#define SYMBOLIC_LINK_QUERY 0x0001
#define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)
#define DUPLICATE_CLOSE_SOURCE 0x00000001
#define DUPLICATE_SAME_ACCESS 0x00000002
#define DUPLICATE_SAME_ATTRIBUTES 0x00000004
// Object attribute defines
#define OBJ_PROTECT_CLOSE 0x00000001L
#define OBJ_INHERIT 0x00000002L
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004L
#define OBJ_PERMANENT 0x00000010L
#define OBJ_EXCLUSIVE 0x00000020L
#define OBJ_CASE_INSENSITIVE 0x00000040L
#define OBJ_OPENIF 0x00000080L
#define OBJ_OPENLINK 0x00000100L
#define OBJ_KERNEL_HANDLE 0x00000200L
#define OBJ_FORCE_ACCESS_CHECK 0x00000400L
#define OBJ_VALID_ATTRIBUTES 0x000007F2L
//#define OBJ_VALID_ATTRIBUTES_KRNL 0x00001FF2L
#define InitializeObjectAttributes(p, n, a, r, s) { \
(p)->Length = sizeof(OBJECT_ATTRIBUTES); \
(p)->RootDirectory = r; \
(p)->Attributes = a; \
(p)->ObjectName = n; \
(p)->SecurityDescriptor = s; \
(p)->SecurityQualityOfService = NULL; \
}
#define InitializeObjectAttributes64(p,n,a,r,s) { \
(p)->Length = sizeof(_OBJECT_ATTRIBUTES64); \
(p)->RootDirectory = r; \
(p)->Attributes = a; \
(p)->ObjectName = n; \
(p)->SecurityDescriptor = s; \
(p)->SecurityQualityOfService = NULL; \
}
#define InitializeObjectAttributes32(p,n,a,r,s) { \
(p)->Length = sizeof(_OBJECT_ATTRIBUTES32); \
(p)->RootDirectory = r; \
(p)->Attributes = a; \
(p)->ObjectName = n; \
(p)->SecurityDescriptor = s; \
(p)->SecurityQualityOfService = NULL; \
}
///
/// < Objects Enums >
///
enum _KOBJECTS
{
EventNotificationObject = 0x0,
EventSynchronizationObject = 0x1,
MutantObject = 0x2,
ProcessObject = 0x3,
QueueObject = 0x4,
SemaphoreObject = 0x5,
ThreadObject = 0x6,
GateObject = 0x7,
TimerNotificationObject = 0x8,
TimerSynchronizationObject = 0x9,
Spare2Object = 0xa,
Spare3Object = 0xb,
Spare4Object = 0xc,
Spare5Object = 0xd,
Spare6Object = 0xe,
Spare7Object = 0xf,
Spare8Object = 0x10,
Spare9Object = 0x11,
ApcObject = 0x12,
DpcObject = 0x13,
DeviceQueueObject = 0x14,
EventPairObject = 0x15,
InterruptObject = 0x16,
ProfileObject = 0x17,
ThreadedDpcObject = 0x18,
MaximumKernelObject = 0x19,
};
///
/// < Objects Routines >
///
typedef NTSTATUS(NTAPI *tNtDuplicateObject)(
IN HANDLE SourceProcessHandle,
IN HANDLE SourceHandle,
IN HANDLE TargetProcessHandle OPTIONAL,
OUT PHANDLE TargetHandle OPTIONAL,
IN ACCESS_MASK DesiredAccess,
IN ULONG HandleAttributes,
IN ULONG Options
);
typedef NTSTATUS(NTAPI *tNtMakeTemporaryObject)(
IN HANDLE Handle
);
typedef NTSTATUS(NTAPI *tNtMakePermanentObject)(
IN HANDLE Handle
);
typedef NTSTATUS(NTAPI *tNtSignalAndWaitForSingleObject)(
IN HANDLE SignalHandle,
IN HANDLE WaitHandle,
IN BOOLEAN Alertable,
IN PLARGE_INTEGER Timeout OPTIONAL
);
typedef NTSTATUS(NTAPI *tNtWaitForSingleObject)(
IN HANDLE Handle,
IN BOOLEAN Alertable,
IN PLARGE_INTEGER Timeout OPTIONAL
);
typedef NTSTATUS(NTAPI *tNtWaitForMultipleObjects)(
IN ULONG Count,
IN HANDLE Handles[],
IN WAIT_TYPE WaitType,
IN BOOLEAN Alertable,
IN PLARGE_INTEGER Timeout OPTIONAL
);
#if (NTDDI_VERSION >= NTDDI_WS03)
typedef NTSTATUS(NTAPI *tNtWaitForMultipleObjects32)(
IN ULONG Count,
IN LONG Handles[],
IN WAIT_TYPE WaitType,
IN BOOLEAN Alertable,
IN PLARGE_INTEGER Timeout OPTIONAL
);
#endif
typedef NTSTATUS(NTAPI *tNtSetSecurityObject)(
IN HANDLE Handle,
IN SECURITY_INFORMATION SecurityInformation,
IN PSECURITY_DESCRIPTOR SecurityDescriptor
);
typedef NTSTATUS(NTAPI *tNtQuerySecurityObject)(
IN HANDLE Handle,
IN SECURITY_INFORMATION SecurityInformation,
IN OUT PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL,
IN ULONG Length,
OUT PULONG LengthNeeded
);
typedef NTSTATUS(NTAPI *tNtClose)(
IN HANDLE Handle
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
typedef NTSTATUS(NTAPI *tNtCompareObjects)(
IN HANDLE FirstObjectHandle,
IN HANDLE SecondObjectHandle
);
#endif
typedef NTSTATUS(NTAPI *tNtCreateSymbolicLinkObject)(
OUT PHANDLE LinkHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PUNICODE_STRING LinkTarget
);
typedef NTSTATUS(NTAPI *tNtOpenSymbolicLinkObject)(
OUT PHANDLE LinkHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
typedef NTSTATUS(NTAPI *tNtQuerySymbolicLinkObject)(
IN HANDLE LinkHandle,
IN OUT PUNICODE_STRING LinkTarget,
OUT PULONG ReturnedLength OPTIONAL
);
| 24.592965 | 65 | 0.757662 | [
"object"
] |
08c4d9e8a3ea11e4c0653b11567fce089864af9d | 6,623 | h | C | src/platform/haswell/include/platform/memory.h | kv2019i/sof | 5ea5da80dd66a916db092de1bc3e090b0095e4f8 | [
"BSD-3-Clause"
] | 1 | 2021-04-27T11:24:46.000Z | 2021-04-27T11:24:46.000Z | src/platform/haswell/include/platform/memory.h | kv2019i/sof | 5ea5da80dd66a916db092de1bc3e090b0095e4f8 | [
"BSD-3-Clause"
] | null | null | null | src/platform/haswell/include/platform/memory.h | kv2019i/sof | 5ea5da80dd66a916db092de1bc3e090b0095e4f8 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Intel Corporation nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Liam Girdwood <liam.r.girdwood@linux.intel.com>
*/
#ifndef __PLATFORM_MEMORY_H__
#define __PLATFORM_MEMORY_H__
#include <config.h>
#include <arch/memory.h>
#if !defined(__ASSEMBLER__) && !defined(LINKER)
void platform_init_memmap(void);
#endif
/* physical DSP addresses */
#define SHIM_SIZE 0x00001000
#define IRAM_BASE 0x00000000
#define IRAM_SIZE 0x00050000
#define DRAM0_BASE 0x00400000
#define DRAM0_VBASE 0x00400000
#define MAILBOX_SIZE 0x00001000
#define DMA0_SIZE 0x00001000
#define DMA1_SIZE 0x00001000
#define SSP0_SIZE 0x00001000
#define SSP1_SIZE 0x00001000
#if CONFIG_BROADWELL
#define DRAM0_SIZE 0x000A0000
#define SHIM_BASE 0xFFFFB000
#define DMA0_BASE 0xFFFFE000
#define DMA1_BASE 0xFFFFF000
#define SSP0_BASE 0xFFFFC000
#define SSP1_BASE 0xFFFFD000
#else /* HASWELL */
#define DRAM0_SIZE 0x00080000
#define SHIM_BASE 0xFFFE7000
#define DMA0_BASE 0xFFFF0000
#define DMA1_BASE 0xFFFF8000
#define SSP0_BASE 0xFFFE8000
#define SSP1_BASE 0xFFFE9000
#endif
#define LOG_ENTRY_ELF_BASE 0x20000000
#define LOG_ENTRY_ELF_SIZE 0x2000000
/*
* The Heap and Stack on Haswell/Broadwell are organised like this :-
*
* +--------------------------------------------------------------------------+
* | Offset | Region | Size |
* +---------------------+----------------+-----------------------------------+
* | DRAM0_BASE | RO Data | SOF_DATA_SIZE |
* | | Data | |
* | | BSS | |
* +---------------------+----------------+-----------------------------------+
* | HEAP_SYSTEM_BASE | System Heap | HEAP_SYSTEM_SIZE |
* +---------------------+----------------+-----------------------------------+
* | HEAP_RUNTIME_BASE | Runtime Heap | HEAP_RUNTIME_SIZE |
* +---------------------+----------------+-----------------------------------+
* | HEAP_BUFFER_BASE | Module Buffers | HEAP_BUFFER_SIZE |
* +---------------------+----------------+-----------------------------------+
* | MAILBOX_BASE | Mailbox | MAILBOX_SIZE |
* +---------------------+----------------+-----------------------------------+
* | SOF_STACK_END | Stack | SOF_STACK_SIZE |
* +---------------------+----------------+-----------------------------------+
* | SOF_STACK_BASE | | |
* +---------------------+----------------+-----------------------------------+
*/
/* Heap section sizes for module pool */
#define HEAP_RT_COUNT8 0
#define HEAP_RT_COUNT16 192
#define HEAP_RT_COUNT32 128
#define HEAP_RT_COUNT64 64
#define HEAP_RT_COUNT128 64
#define HEAP_RT_COUNT256 64
#define HEAP_RT_COUNT512 8
#define HEAP_RT_COUNT1024 4
/* Heap section sizes for system runtime heap */
#define HEAP_SYS_RT_COUNT64 64
#define HEAP_SYS_RT_COUNT512 8
#define HEAP_SYS_RT_COUNT1024 4
/* Heap configuration */
#define SOF_DATA_SIZE 0xa000
#define HEAP_SYSTEM_BASE (DRAM0_BASE + SOF_DATA_SIZE)
#define HEAP_SYSTEM_SIZE 0x3000
#define HEAP_SYSTEM_0_BASE HEAP_SYSTEM_BASE
#define HEAP_SYS_RUNTIME_BASE (HEAP_SYSTEM_BASE + HEAP_SYSTEM_SIZE)
#define HEAP_SYS_RUNTIME_SIZE \
(HEAP_SYS_RT_COUNT64 * 64 + HEAP_SYS_RT_COUNT512 * 512 + \
HEAP_SYS_RT_COUNT1024 * 1024)
#define HEAP_RUNTIME_BASE (HEAP_SYS_RUNTIME_BASE + HEAP_SYS_RUNTIME_SIZE)
#define HEAP_RUNTIME_SIZE \
(HEAP_RT_COUNT8 * 8 + HEAP_RT_COUNT16 * 16 + \
HEAP_RT_COUNT32 * 32 + HEAP_RT_COUNT64 * 64 + \
HEAP_RT_COUNT128 * 128 + HEAP_RT_COUNT256 * 256 + \
HEAP_RT_COUNT512 * 512 + HEAP_RT_COUNT1024 * 1024)
#define HEAP_BUFFER_BASE (HEAP_RUNTIME_BASE + HEAP_RUNTIME_SIZE)
#define HEAP_BUFFER_SIZE \
(DRAM0_SIZE - HEAP_RUNTIME_SIZE - SOF_STACK_TOTAL_SIZE -\
HEAP_SYS_RUNTIME_SIZE - HEAP_SYSTEM_SIZE - SOF_DATA_SIZE -\
MAILBOX_SIZE)
#define HEAP_BUFFER_BLOCK_SIZE 0x180
#define HEAP_BUFFER_COUNT (HEAP_BUFFER_SIZE / HEAP_BUFFER_BLOCK_SIZE)
#define PLATFORM_HEAP_SYSTEM 1 /* one per core */
#define PLATFORM_HEAP_SYSTEM_RUNTIME 1 /* one per core */
#define PLATFORM_HEAP_RUNTIME 1
#define PLATFORM_HEAP_BUFFER 1
/* Stack configuration */
#define SOF_STACK_SIZE ARCH_STACK_SIZE
#define SOF_STACK_TOTAL_SIZE ARCH_STACK_TOTAL_SIZE
#define SOF_STACK_BASE (DRAM0_BASE + DRAM0_SIZE)
#define SOF_STACK_END (SOF_STACK_BASE - SOF_STACK_TOTAL_SIZE)
#define MAILBOX_BASE (SOF_STACK_END - MAILBOX_SIZE)
/* Vector and literal sizes - not in core-isa.h */
#define SOF_MEM_VECT_LIT_SIZE 0x4
#define SOF_MEM_VECT_TEXT_SIZE 0x1c
#define SOF_MEM_VECT_SIZE (SOF_MEM_VECT_TEXT_SIZE + SOF_MEM_VECT_LIT_SIZE)
#define SOF_MEM_RESET_TEXT_SIZE 0x2e0
#define SOF_MEM_RESET_LIT_SIZE 0x120
#define SOF_MEM_VECBASE_LIT_SIZE 0x178
#define SOF_MEM_RO_SIZE 0x8
#define uncache_to_cache(address) address
#define cache_to_uncache(address) address
#define is_uncached(address) 0
#endif
| 37.418079 | 80 | 0.653027 | [
"vector"
] |
08c82430bc780c4b0be9227ce56959b4a2dfb2cc | 1,942 | h | C | src/schematiceditor/device.h | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | src/schematiceditor/device.h | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | src/schematiceditor/device.h | schdesign/board-builder | 9b4f56e38dbf6e8ffabab5fcdb9fda834fd00226 | [
"MIT"
] | null | null | null | // device.h
// Copyright (C) 2018 Alexander Karpeko
#ifndef DEVICE_H
#define DEVICE_H
#include "unit.h"
#include <QJsonObject>
#include <QJsonValue>
class DevicePin
{
public:
DevicePin() {}
DevicePin(int x, int y, QString name, bool side, int unit):
x(x), y(y), name(name), side(side), unit(unit) {}
DevicePin(const QJsonValue &value);
QJsonObject toJson();
int x;
int y;
QString name;
bool side; // 0: left, 1: right
int unit; // unit number
};
class DeviceSymbol
{
public:
QJsonObject toJson();
bool showPinName;
int nameID;
int pinNameXLeft;
int pinNameXRight;
int pinNameY;
int type;
int unitsNumber;
QString name;
QString packageName;
QString reference;
Unit unit;
std::vector<DevicePin> pins;
};
class Device
{
public:
Device() {}
Device(int symbolNameID, int refX, int refY);
Device(const QString &name, int symbolNameID, int refX, int refY);
Device(const QJsonObject &object);
static void addSymbol(const QJsonValue &value);
static QJsonObject writeSymbols();
void draw(QPainter &painter, int fontSize);
int exist(int x, int y);
void init();
bool inside(int leftX, int topY, int rightX, int bottomY,
std::vector<int> &unitNumbers);
QJsonObject toJson();
static int symbolID;
static std::map <int, DeviceSymbol> symbols; // device nameID, deviceSymbol
bool showPinName;
int center; // device center is center of 1st unit
int symbolNameID;
int pinNameXLeft;
int pinNameXRight;
int pinNameY;
int referenceType; // D
int refX; // point of top left pin of 1st unit
int refY;
int type;
int unitsNumber;
QString name;
QString packageName;
QString reference; // D1
QString symbolName;
Unit unit;
std::vector<DevicePin> pins;
std::vector<Unit> units;
};
#endif // DEVICE_H
| 22.847059 | 80 | 0.643666 | [
"object",
"vector"
] |
08d4b0a51dd83554dcb2e58facf94c0908eff8b6 | 23,580 | h | C | sdk-6.5.16/include/bcm/multicast.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.16/include/bcm/multicast.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.16/include/bcm/multicast.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /*
*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*
* DO NOT EDIT THIS FILE!
* This file is auto-generated.
* Edits to this file will be lost when it is regenerated.
*/
#ifndef __BCM_MULTICAST_H__
#define __BCM_MULTICAST_H__
#include <bcm/types.h>
#include <shared/multicast.h>
#define BCM_MULTICAST_INVALID 0
/* Mulicast flags. */
#define BCM_MULTICAST_WITH_ID 0x00000001
#define BCM_MULTICAST_TYPE_L2 0x00010000
#define BCM_MULTICAST_TYPE_L3 0x00020000
#define BCM_MULTICAST_TYPE_VPLS 0x00040000
#define BCM_MULTICAST_TYPE_SUBPORT 0x00080000
#define BCM_MULTICAST_TYPE_MIM 0x00100000
#define BCM_MULTICAST_TYPE_WLAN 0x00200000
#define BCM_MULTICAST_TYPE_VLAN 0x00400000
#define BCM_MULTICAST_TYPE_TRILL 0x00800000
#define BCM_MULTICAST_TYPE_NIV 0x01000000
#define BCM_MULTICAST_TYPE_EGRESS_OBJECT 0x02000000
#define BCM_MULTICAST_TYPE_L2GRE 0x04000000
#define BCM_MULTICAST_TYPE_VXLAN 0x08000000
#define BCM_MULTICAST_TYPE_EXTENDER 0x10000000
#define BCM_MULTICAST_TYPE_MAC 0x20000000
#define BCM_MULTICAST_TYPE_PORTS_GROUP 0x40000000
#define BCM_MULTICAST_TYPE_FLOW 0x80000000
#define BCM_MULTICAST_TYPE_MASK 0xffff0000
#define BCM_MULTICAST_DISABLE_SRC_KNOCKOUT 0x00000002
#define BCM_MULTICAST_INGRESS_GROUP 0x00000004
#define BCM_MULTICAST_EGRESS_GROUP 0x00000008
#define BCM_MULTICAST_INGRESS_MMC_BUFFERS 0x00000010
/* Multicast Type (for bcm_multicast_type). */
typedef enum bcm_multicast_type_e {
bcmMulticastTypeL2 = 1, /* Multicast type L2 */
bcmMulticastTypeL3 = 2, /* Multicast type L3 */
bcmMulticastTypeVpls = 3, /* Multicast type VPLS */
bcmMulticastTypeSubPort = 4, /* Multicast type Sub Port */
bcmMulticastTypeMim = 5, /* Multicast type MIM */
bcmMulticastTypeWlan = 6, /* Multicast type Wlan */
bcmMulticastTypeVlan = 7, /* Multicast type Vlan */
bcmMulticastTypeTrill = 8, /* Multicast type TRILL */
bcmMulticastTypeNiv = 9, /* Multicast type NIV */
bcmMulticastTypeEgressObject = 10, /* Multicast type Egress Object */
bcmMulticastTypeL2Gre = 11, /* Multicast type L2 GRE */
bcmMulticastTypeVxlan = 12, /* Multicast type Vxlan */
bcmMulticastTypePortsGroup = 13, /* Multicast type Ports Group */
bcmMulticastTypeExtender = 14, /* Multicast type Extender */
bcmMulticastTypeMac = 15, /* Multicast type MAC */
bcmMulticastTypeFlow = 16, /* Multicast type Flow */
bcmMulticastTypeCount = 17 /* Multicast type Count */
} bcm_multicast_type_t;
#define BCM_MULTICASTTYPE_STRINGS \
{ \
"L2", \
"L3", \
"Vpls", \
"SubPort", \
"Mim", \
"Wlan", \
"Vlan", \
"Trill", \
"Niv", \
"EgressObject", \
"L2Gre", \
"Vxlan", \
"PortsGroup", \
"Extender", \
"Mac", \
"Flow", \
"Count" \
}
#define BCM_MULTICAST_IS_SET(group) _SHR_MULTICAST_IS_SET(group)
#define BCM_MULTICAST_IS_L2(group) _SHR_MULTICAST_IS_L2(group)
#define BCM_MULTICAST_IS_L3(group) _SHR_MULTICAST_IS_L3(group)
#define BCM_MULTICAST_IS_VPLS(group) _SHR_MULTICAST_IS_VPLS(group)
#define BCM_MULTICAST_IS_SUBPORT(group) _SHR_MULTICAST_IS_SUBPORT(group)
#define BCM_MULTICAST_IS_MIM(group) _SHR_MULTICAST_IS_MIM(group)
#define BCM_MULTICAST_IS_WLAN(group) _SHR_MULTICAST_IS_WLAN(group)
#define BCM_MULTICAST_IS_VLAN(group) _SHR_MULTICAST_IS_VLAN(group)
#define BCM_MULTICAST_IS_TRILL(group) _SHR_MULTICAST_IS_TRILL(group)
#define BCM_MULTICAST_IS_NIV(group) _SHR_MULTICAST_IS_NIV(group)
#define BCM_MULTICAST_IS_EGRESS_OBJECT(group) _SHR_MULTICAST_IS_EGRESS_OBJECT(group)
#define BCM_MULTICAST_IS_L2GRE(group) _SHR_MULTICAST_IS_L2GRE(group)
#define BCM_MULTICAST_IS_VXLAN(group) _SHR_MULTICAST_IS_VXLAN(group)
#define BCM_MULTICAST_IS_FLOW(group) _SHR_MULTICAST_IS_FLOW(group)
#define BCM_MULTICAST_IS_PORTS_GROUP(group) _SHR_MULTICAST_IS_PORTS_GROUP(group)
#define BCM_MULTICAST_IS_EXTENDER(group) _SHR_MULTICAST_IS_EXTENDER(group)
#define BCM_MULTICAST_L2_SET(group, mc_index) _SHR_MULTICAST_L2_SET(group, mc_index)
#define BCM_MULTICAST_L3_SET(group, mc_index) _SHR_MULTICAST_L3_SET(group, mc_index)
#define BCM_MULTICAST_VPLS_SET(group, mc_index) _SHR_MULTICAST_VPLS_SET(group, mc_index)
#define BCM_MULTICAST_SUBPORT_SET(group, mc_index) _SHR_MULTICAST_SUBPORT_SET(group, mc_index)
#define BCM_MULTICAST_MIM_SET(group, mc_index) _SHR_MULTICAST_MIM_SET(group, mc_index)
#define BCM_MULTICAST_WLAN_SET(group, mc_index) _SHR_MULTICAST_WLAN_SET(group, mc_index)
#define BCM_MULTICAST_VLAN_SET(group, mc_index) _SHR_MULTICAST_VLAN_SET(group, mc_index)
#define BCM_MULTICAST_TRILL_SET(group, mc_index) _SHR_MULTICAST_TRILL_SET(group, mc_index)
#define BCM_MULTICAST_NIV_SET(group, mc_index) _SHR_MULTICAST_NIV_SET(group, mc_index)
#define BCM_MULTICAST_EGRESS_OBJECT_SET(group, mc_index) _SHR_MULTICAST_EGRESS_OBJECT_SET(group, mc_index)
#define BCM_MULTICAST_L2GRE_SET(group, mc_index) _SHR_MULTICAST_L2GRE_SET(group, mc_index)
#define BCM_MULTICAST_VXLAN_SET(group, mc_index) _SHR_MULTICAST_VXLAN_SET(group, mc_index)
#define BCM_MULTICAST_FLOW_SET(group, mc_index) _SHR_MULTICAST_FLOW_SET(group, mc_index)
#define BCM_MULTICAST_PORTS_GROUP_SET(group, mc_index) _SHR_MULTICAST_PORTS_GROUP_SET(group, mc_index)
#define BCM_MULTICAST_EXTENDER_SET(group, mc_index) _SHR_MULTICAST_EXTENDER_SET(group, mc_index)
#define BCM_MULTICAST_L2_GET(group) _SHR_MULTICAST_L2_GET(group)
#define BCM_MULTICAST_L3_GET(group) _SHR_MULTICAST_L3_GET(group)
#define BCM_MULTICAST_VPLS_GET(group) _SHR_MULTICAST_VPLS_GET(group)
#define BCM_MULTICAST_SUBPORT_GET(group) _SHR_MULTICAST_SUBPORT_GET(group)
#define BCM_MULTICAST_MIM_GET(group) _SHR_MULTICAST_MIM_GET(group)
#define BCM_MULTICAST_WLAN_GET(group) _SHR_MULTICAST_WLAN_GET(group)
#define BCM_MULTICAST_VLAN_GET(group) _SHR_MULTICAST_VLAN_GET(group)
#define BCM_MULTICAST_TRILL_GET(group) _SHR_MULTICAST_TRILL_GET(group)
#define BCM_MULTICAST_NIV_GET(group) _SHR_MULTICAST_NIV_GET(group)
#define BCM_MULTICAST_EGRESS_OBJECT_GET(group) _SHR_MULTICAST_EGRESS_OBJECT_GET(group)
#define BCM_MULTICAST_L2GRE_GET(group) _SHR_MULTICAST_L2GRE_GET(group)
#define BCM_MULTICAST_VXLAN_GET(group) _SHR_MULTICAST_VXLAN_GET(group)
#define BCM_MULTICAST_FLOW_GET(group) _SHR_MULTICAST_FLOW_GET(group)
#define BCM_MULTICAST_PORTS_GROUP_GET(group) _SHR_MULTICAST_PORTS_GROUP_GET(group)
#define BCM_MULTICAST_EXTENDER_GET(group) _SHR_MULTICAST_EXTENDER_GET(group)
#define BCM_MULTICAST_L2(mc_index) _SHR_MULTICAST_L2(mc_index)
#define BCM_MULTICAST_L3(mc_index) _SHR_MULTICAST_L3(mc_index)
#define BCM_MULTICAST_VPLS(mc_index) _SHR_MULTICAST_VPLS(mc_index)
#define BCM_MULTICAST_SUBPORT(mc_index) _SHR_MULTICAST_SUBPORT(mc_index)
#define BCM_MULTICAST_MIM(mc_index) _SHR_MULTICAST_MIM(mc_index)
#define BCM_MULTICAST_WLAN(mc_index) _SHR_MULTICAST_WLAN(mc_index)
#define BCM_MULTICAST_VLAN(mc_index) _SHR_MULTICAST_VLAN(mc_index)
#define BCM_MULTICAST_TRILL(mc_index) _SHR_MULTICAST_TRILL(mc_index)
#define BCM_MULTICAST_NIV(mc_index) _SHR_MULTICAST_NIV(mc_index)
#define BCM_MULTICAST_EGRESS_OBJECT(mc_index) _SHR_MULTICAST_EGRESS_OBJECT(mc_index)
#define BCM_MULTICAST_L2GRE(mc_index) _SHR_MULTICAST_L2GRE(mc_index)
#define BCM_MULTICAST_VXLAN(mc_index) _SHR_MULTICAST_VXLAN(mc_index)
#define BCM_MULTICAST_FLOW(mc_index) _SHR_MULTICAST_FLOW(mc_index)
#define BCM_MULTICAST_PORTS_GROUP(mc_index) _SHR_MULTICAST_PORTS_GROUP(mc_index)
#define BCM_MULTICAST_EXTENDER(mc_index) _SHR_MULTICAST_EXTENDER(mc_index)
#define BCM_MULTICAST_TYPE(group) _SHR_MULTICAST_TYPE(group)
#ifndef BCM_HIDE_DISPATCHABLE
/* Initialize the multicast module. */
extern int bcm_multicast_init(
int unit);
/* Shut down (uninitialize) the multicast module. */
extern int bcm_multicast_detach(
int unit);
/* bcm_multicast_create */
extern int bcm_multicast_create(
int unit,
uint32 flags,
bcm_multicast_t *group);
/* bcm_multicast_destroy */
extern int bcm_multicast_destroy(
int unit,
bcm_multicast_t group);
/* bcm_multicast_fabric_distribution_set */
extern int bcm_multicast_fabric_distribution_set(
int unit,
bcm_multicast_t group,
bcm_fabric_distribution_t ds_id);
/* bcm_multicast_fabric_distribution_get */
extern int bcm_multicast_fabric_distribution_get(
int unit,
bcm_multicast_t group,
bcm_fabric_distribution_t *ds_id);
/* bcm_multicast_l3_encap_get */
extern int bcm_multicast_l3_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t intf,
bcm_if_t *encap_id);
/* bcm_multicast_l2_encap_get */
extern int bcm_multicast_l2_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_vlan_t vlan,
bcm_if_t *encap_id);
/* bcm_multicast_vpls_encap_get */
extern int bcm_multicast_vpls_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t mpls_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_trill_encap_get */
extern int bcm_multicast_trill_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t intf,
bcm_if_t *encap_id);
/* bcm_multicast_subport_encap_get */
extern int bcm_multicast_subport_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t subport,
bcm_if_t *encap_id);
/* bcm_multicast_mim_encap_get */
extern int bcm_multicast_mim_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t mim_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_wlan_encap_get */
extern int bcm_multicast_wlan_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t wlan_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_vlan_encap_get */
extern int bcm_multicast_vlan_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t vlan_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_niv_encap_get */
extern int bcm_multicast_niv_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t niv_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_egress_object_encap_get */
extern int bcm_multicast_egress_object_encap_get(
int unit,
bcm_multicast_t group,
bcm_if_t intf,
bcm_if_t *encap_id);
/* bcm_multicast_l2gre_encap_get */
extern int bcm_multicast_l2gre_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t l2gre_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_vxlan_encap_get */
extern int bcm_multicast_vxlan_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t vxlan_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_extender_encap_get */
extern int bcm_multicast_extender_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t extender_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_mac_encap_get */
extern int bcm_multicast_mac_encap_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t mac_port_id,
bcm_if_t *encap_id);
/* bcm_multicast_egress_add */
extern int bcm_multicast_egress_add(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id);
/* bcm_multicast_egress_subscriber_add */
extern int bcm_multicast_egress_subscriber_add(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id,
bcm_gport_t subscriber_queue);
/* bcm_multicast_egress_delete */
extern int bcm_multicast_egress_delete(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id);
/* bcm_multicast_egress_subscriber_delete */
extern int bcm_multicast_egress_subscriber_delete(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id,
bcm_gport_t subscriber_queue);
/* bcm_multicast_egress_delete_all */
extern int bcm_multicast_egress_delete_all(
int unit,
bcm_multicast_t group);
/* bcm_multicast_egress_set */
extern int bcm_multicast_egress_set(
int unit,
bcm_multicast_t group,
int port_count,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array);
/* bcm_multicast_egress_subscriber_set */
extern int bcm_multicast_egress_subscriber_set(
int unit,
bcm_multicast_t group,
int port_count,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array,
bcm_gport_t *subscriber_queue_array);
/* bcm_multicast_egress_get */
extern int bcm_multicast_egress_get(
int unit,
bcm_multicast_t group,
int port_max,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array,
int *port_count);
/* bcm_multicast_egress_subscriber_get */
extern int bcm_multicast_egress_subscriber_get(
int unit,
bcm_multicast_t group,
int port_max,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array,
bcm_gport_t *subscriber_queue_array,
int *port_count);
/* bcm_multicast_egress_subscriber_qos_map_set */
extern int bcm_multicast_egress_subscriber_qos_map_set(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t subscriber_queue,
int qos_map_id);
/* bcm_multicast_egress_subscriber_qos_map_get */
extern int bcm_multicast_egress_subscriber_qos_map_get(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_gport_t subscriber_queue,
int *qos_map_id);
/* bcm_multicast_ingress_add */
extern int bcm_multicast_ingress_add(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id);
/* bcm_multicast_egress_delete */
extern int bcm_multicast_ingress_delete(
int unit,
bcm_multicast_t group,
bcm_gport_t port,
bcm_if_t encap_id);
/* bcm_multicast_egress_delete_all */
extern int bcm_multicast_ingress_delete_all(
int unit,
bcm_multicast_t group);
/* bcm_multicast_ingress_set */
extern int bcm_multicast_ingress_set(
int unit,
bcm_multicast_t group,
int port_count,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array);
/* bcm_multicast_ingress_get */
extern int bcm_multicast_ingress_get(
int unit,
bcm_multicast_t group,
int port_max,
bcm_gport_t *port_array,
bcm_if_t *encap_id_array,
int *port_count);
/* Assign a set of VLANs as the selected port's replication list. */
extern int bcm_multicast_repl_set(
int unit,
int mc_index,
bcm_port_t port,
bcm_vlan_vector_t vlan_vec);
/* Return set of VLANs selected for port's replication list. */
extern int bcm_multicast_repl_get(
int unit,
int index,
bcm_port_t port,
bcm_vlan_vector_t vlan_vec);
/* Retrieve the flags associated with a mulitcast group. */
extern int bcm_multicast_group_get(
int unit,
bcm_multicast_t group,
uint32 *flags);
/* Request if the given multicast group is available on the device */
extern int bcm_multicast_group_is_free(
int unit,
bcm_multicast_t group);
/*
* Retrieve the minimum and maximum unallocated multicast groups for a
* given multicast type.
*/
extern int bcm_multicast_group_free_range_get(
int unit,
uint32 type_flag,
bcm_multicast_t *group_min,
bcm_multicast_t *group_max);
#endif /* BCM_HIDE_DISPATCHABLE */
/* Callback function for bcm_multicast_group_traverse. */
typedef int (*bcm_multicast_group_traverse_cb_t)(
int unit,
bcm_multicast_t group,
uint32 flags,
void *user_data);
#ifndef BCM_HIDE_DISPATCHABLE
/*
* Iterate over the defined multicast groups of the type specified in
* 'flags'. If all types are desired, use MULTICAST_TYPE_MASK.
*/
extern int bcm_multicast_group_traverse(
int unit,
bcm_multicast_group_traverse_cb_t trav_fn,
uint32 flags,
void *user_data);
#endif /* BCM_HIDE_DISPATCHABLE */
/* Multicast group controls. */
typedef enum bcm_multicast_control_e {
bcmMulticastControlMtu = 0, /* Maximum transmission unit. */
bcmMulticastVpTrunkResolve = 1, /* Enable virtual port trunk group
resolution. */
bcmMulticastRemapGroup = 2, /* Remap multicast groups. */
bcmMulticastControlCount = 3 /* Must be last */
} bcm_multicast_control_t;
#ifndef BCM_HIDE_DISPATCHABLE
/* Set multicast group control. */
extern int bcm_multicast_control_set(
int unit,
bcm_multicast_t group,
bcm_multicast_control_t type,
int arg);
/* Get multicast group control. */
extern int bcm_multicast_control_get(
int unit,
bcm_multicast_t group,
bcm_multicast_control_t type,
int *arg);
#endif /* BCM_HIDE_DISPATCHABLE */
/* describes a multicast replication */
typedef struct bcm_multicast_replication_s {
uint32 flags; /* information on the replication */
bcm_gport_t port; /* destination */
bcm_if_t encap1; /* first encapsulation. */
bcm_if_t encap2; /* second encapsulation. */
} bcm_multicast_replication_t;
#define BCM_MUTICAST_REPLICATION_ENCAP2_VALID 1 /* determines if encap2
is used . */
#define BCM_MUTICAST_REPLICATION_ENCAP1_L3_INTF 2 /* when encap2 is used,
determines if encap1
is a routing interface
or not. */
#ifndef BCM_HIDE_DISPATCHABLE
/* get multicast destinations */
extern int bcm_multicast_get(
int unit,
bcm_multicast_t group,
uint32 flags,
int replication_max,
bcm_multicast_replication_t *out_rep_array,
int *rep_count);
/* set multicast destinations */
extern int bcm_multicast_set(
int unit,
bcm_multicast_t group,
uint32 flags,
int nof_replications,
bcm_multicast_replication_t *rep_array);
/* remove multicast destinations */
extern int bcm_multicast_delete(
int unit,
bcm_multicast_t group,
uint32 flags,
int nof_replications,
bcm_multicast_replication_t *rep_array);
/* Add multicast destinations */
extern int bcm_multicast_add(
int unit,
bcm_multicast_t group,
uint32 flags,
int nof_replications,
bcm_multicast_replication_t *rep_array);
#endif /* BCM_HIDE_DISPATCHABLE */
/* init multicast replication struct */
extern void bcm_multicast_replication_t_init(
bcm_multicast_replication_t *replication_structure);
/*
* Can be use for setting flags parameter to
* (bcm_multicast_get,bcm_multicast_set,bcm_multicast_add,bcm_multicast_delete)
*/
#define BCM_MULTICAST_INGRESS 0x00000001
/* L3 Multiple multicast group related flags. */
#define BCM_MULTICAST_MULTI_WITH_ID (1 << 0) /* Create multiple multicast
groups with id. */
#define BCM_MULTICAST_MULTI_TYPE_L3 (1 << 1) /* Create multiple group of
L3 type. */
#define BCM_MULTICAST_MULTI_TYPE_VPLS (1 << 2) /* Create multiple group of
VPLS type. */
/* Information to create multiple multicast groups. */
typedef struct bcm_multicast_multi_info_s {
uint32 flags; /* See BCM_MULTICAST_MULTI_XXX flag definitions. */
int number_of_elements; /* number of multicast groups to allocate. */
} bcm_multicast_multi_info_t;
/* Initialize a multicast multi structure. */
extern void bcm_multicast_multi_info_t_init(
bcm_multicast_multi_info_t *mc_multi_info);
#ifndef BCM_HIDE_DISPATCHABLE
/* Allocate multiple multicast groups. */
extern int bcm_multicast_multi_alloc(
int unit,
bcm_multicast_multi_info_t mc_multi_info,
bcm_multicast_t *base_mc_group);
/* Free multiple multicast groups. */
extern int bcm_multicast_multi_free(
int unit,
bcm_multicast_t base_mc_group);
#endif /* BCM_HIDE_DISPATCHABLE */
#define BCM_MULTICAST_REMOVE_ALL 0x00000010
#define BCM_MULTICAST_BIER_64_GROUP 0x00000010
#define BCM_MULTICAST_BIER_128_GROUP 0x00000020
#define BCM_MULTICAST_BIER_256_GROUP 0x00000040
#define BCM_MULICAST_STAT_EXTERNAL 0x00000001 /* Used to indicate of updating
multicast external statistics
parameters. */
/* Multicast statistics control types. */
typedef enum bcm_multicast_stat_control_type_e {
bcmMulticastStatControlCountAllCopiesAsOne = 0
} bcm_multicast_stat_control_type_t;
#ifndef BCM_HIDE_DISPATCHABLE
/* Multicast statistics control set API. */
extern int bcm_multicast_stat_control_set(
int unit,
bcm_core_t core_id,
uint32 flags,
int command_id,
bcm_multicast_stat_control_type_t type,
int arg);
/* Multicast statistics control get API. */
extern int bcm_multicast_stat_control_get(
int unit,
bcm_core_t core_id,
uint32 flags,
int command_id,
bcm_multicast_stat_control_type_t type,
int *arg);
#endif /* BCM_HIDE_DISPATCHABLE */
/* Multicast Encap extension flags */
#define BCM_MULTICAST_ENCAP_EXTENSION_REPLACE 0x00000001 /* Replace an existing
entry in encapsulation
extension table */
#define BCM_MULTICAST_ENCAP_EXTENSION_WITH_ID 0x00000002 /* Indicate creation with
a given ID. */
#ifndef BCM_HIDE_DISPATCHABLE
/* Allows the MC replication to use more than a single encapsulation. */
extern int bcm_multicast_encap_extension_create(
int unit,
uint32 flags,
bcm_if_t *multicast_replication_index,
int encap_extension_count,
bcm_if_t *encap_extension_array);
/*
* Return the encapsulation IDs that are placed in the encapsulation
* extension table under the encap_id entry.
*/
extern int bcm_multicast_encap_extension_get(
int unit,
uint32 flags,
bcm_if_t multicast_replication_index,
int encap_max,
bcm_if_t *encap_extension_array,
int *encap_extension_count);
/* Delete an entry from the encapsulation table. */
extern int bcm_multicast_encap_extension_destroy(
int unit,
uint32 flags,
bcm_if_t multicast_replication_index);
/* Delete all the members from the encapsulation extension table. */
extern int bcm_multicast_encap_extension_delete_all(
int unit);
#endif /* BCM_HIDE_DISPATCHABLE */
/* Callback function for bcm_multicast_encap_extension_traverse. */
typedef int (*bcm_multicast_encap_extension_traverse_cb)(
int unit,
bcm_if_t multicast_replication_index,
uint32 flags,
void *user_data);
#ifndef BCM_HIDE_DISPATCHABLE
/* Traverse over all the entries in the encapsulation extension table */
extern int bcm_multicast_encap_extension_traverse(
int unit,
bcm_multicast_encap_extension_traverse_cb trav_fn,
void *user_data);
#endif /* BCM_HIDE_DISPATCHABLE */
#endif /* __BCM_MULTICAST_H__ */
| 33.782235 | 134 | 0.732103 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.