Coverage for cuda/core/texture/_texture.pyx: 93.26%

282 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-07-19 01:12 +0000

1# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 

2# 

3# SPDX-License-Identifier: Apache-2.0 

4  

5from __future__ import annotations 

6  

7from libc.stdint cimport intptr_t 

8from libc.string cimport memset 

9  

10from cuda.bindings cimport cydriver 

11from cuda.core.texture._array cimport OpaqueArray 

12from cuda.core.texture._array import ( 

13 _ARRAYFORMAT_TO_CU, 

14 _CU_TO_ARRAYFORMAT, 

15 _FORMAT_ELEM_SIZE, 

16 _validate_format_channels, 

17) 

18from cuda.core._memory._buffer cimport Buffer 

19from cuda.core.texture._mipmapped_array cimport MipmappedArray 

20from cuda.core.texture._mipmapped_array import MipmappedArray as _PyMipmappedArray 

21from cuda.core._resource_handles cimport ( 

22 TexObjectHandle, 

23 as_cu, 

24 as_intptr, 

25 create_tex_object_handle_array, 

26 create_tex_object_handle_linear, 

27 create_tex_object_handle_mipmap, 

28 get_last_error, 

29) 

30from cuda.core._utils.cuda_utils cimport ( 

31 HANDLE_RETURN, 

32 _get_current_device_id, 

33) 

34  

35from cuda.core.typing import AddressModeType, FilterModeType, ReadModeType 

36  

37from dataclasses import dataclass 

38  

39from cuda.core._utils.cuda_utils import check_or_create_options 

40  

41  

42# Driver texture-descriptor flag bits (CU_TRSF_*). 

43_TRSF_READ_AS_INTEGER = 0x01 

44_TRSF_NORMALIZED_COORDINATES = 0x02 

45_TRSF_SRGB = 0x10 

46_TRSF_DISABLE_TRILINEAR_OPTIMIZATION = 0x20 

47_TRSF_SEAMLESS_CUBEMAP = 0x40 

48  

49  

50# Bridge between the public sampling StrEnums and the driver integer values. 

51_ADDRESSMODE_TO_CU = { 

52 AddressModeType.WRAP: int(cydriver.CU_TR_ADDRESS_MODE_WRAP), 

53 AddressModeType.CLAMP: int(cydriver.CU_TR_ADDRESS_MODE_CLAMP), 

54 AddressModeType.MIRROR: int(cydriver.CU_TR_ADDRESS_MODE_MIRROR), 

55 AddressModeType.BORDER: int(cydriver.CU_TR_ADDRESS_MODE_BORDER), 

56} 

57_FILTERMODE_TO_CU = { 

58 FilterModeType.POINT: int(cydriver.CU_TR_FILTER_MODE_POINT), 

59 FilterModeType.LINEAR: int(cydriver.CU_TR_FILTER_MODE_LINEAR), 

60} 

61  

62  

63def _normalize_enum(name, value, enum_type): 

64 """Coerce ``value`` to ``enum_type`` (a StrEnum), accepting a plain str.""" 

65 if isinstance(value, enum_type): 1cmknoebdafiGtBjDg

66 return value 1cmknoebdafitBjDg

67 try: 1kGtB

68 return enum_type(value) 1kGtB

69 except ValueError as e: 1kGtB

70 valid = ", ".join(repr(m.value) for m in enum_type) 1kGtB

71 raise ValueError( 1kGtB

72 f"{name} must be a {enum_type.__name__} or one of {{{valid}}}, got {value!r}" 1kGtB

73 ) from e 1kGtB

74  

75  

76class ResourceDescriptor: 

77 """Describes the memory backing a :class:`TextureObject`. 

78  

79 Construct via the ``from_*`` classmethods: 

80  

81 - :meth:`from_opaque_array` wraps a :class:`OpaqueArray` (works for both 

82 :class:`TextureObject` and :class:`SurfaceObject`). 

83 - :meth:`from_mipmapped_array` wraps a :class:`MipmappedArray` for mipmapped 

84 sampling (texture only, not surface). 

85 - :meth:`from_linear` wraps a :class:`Buffer` as a typed 1D fetch. Texture 

86 objects built from a linear resource do not support filtering, 

87 normalized coordinates, or addressing modes. 

88 - :meth:`from_pitch2d` wraps a :class:`Buffer` as a row-pitched 2D image. 

89 Supports filtering and 2D addressing, but only 2D access. 

90  

91 Linear and pitch2D resources cannot back a :class:`SurfaceObject` — those 

92 require an :class:`OpaqueArray` allocated with ``is_surface_load_store=True``. 

93  

94 .. versionadded:: 1.1.0 

95 """ 

96  

97 __slots__ = ( 

98 "_kind", "_source", 

99 "_format", "_num_channels", 

100 "_size_bytes", 

101 "_width", "_height", "_pitch_bytes", 

102 ) 

103  

104 def __init__(self): 

105 raise RuntimeError( 1N

106 "ResourceDescriptor cannot be instantiated directly. " 

107 "Use ResourceDescriptor.from_* factories." 

108 ) 

109  

110 @classmethod 

111 def from_opaque_array(cls, array): 

112 """Build a resource descriptor backed by a :class:`OpaqueArray`.""" 

113 if not isinstance(array, OpaqueArray): 1cmknouvwefirjg

114 raise TypeError(f"array must be a OpaqueArray, got {type(array).__name__}") 

115 self = cls.__new__(cls) 1hcmknouvwefirjg

116 self._kind = "array" 1cmknouvwefirjg

117 self._source = array 1cmknouvwefirjg

118 self._format = None 1cmknouvwefirjg

119 self._num_channels = None 1cmknouvwefirjg

120 self._size_bytes = None 1cmknouvwefirjg

121 self._width = None 1cmknouvwefirjg

122 self._height = None 1cmknouvwefirjg

123 self._pitch_bytes = None 1cmknouvwefirjg

124 return self 1cmknouvwefirjg

125  

126 @classmethod 

127 def from_mipmapped_array(cls, mipmapped_array): 

128 """Build a resource descriptor backed by a :class:`MipmappedArray`. 

129  

130 Suitable for binding to a :class:`TextureObject` for mipmapped 

131 sampling. Not valid as a :class:`SurfaceObject` backing: surfaces 

132 require a single :class:`OpaqueArray` level (obtain via 

133 :meth:`MipmappedArray.get_level`). 

134 """ 

135 if not isinstance(mipmapped_array, _PyMipmappedArray): 1HxAd

136 raise TypeError( 1H

137 f"mipmapped_array must be a MipmappedArray, got " 1H

138 f"{type(mipmapped_array).__name__}" 1H

139 ) 

140 self = cls.__new__(cls) 1xAd

141 self._kind = "mipmapped_array" 1xAd

142 self._source = mipmapped_array 1xAd

143 self._format = None 1xAd

144 self._num_channels = None 1xAd

145 self._size_bytes = None 1xAd

146 self._width = None 1xAd

147 self._height = None 1xAd

148 self._pitch_bytes = None 1xAd

149 return self 1xAd

150  

151 @classmethod 

152 def from_linear(cls, buffer, *, format, num_channels, size_bytes=None): 

153 """Build a resource descriptor for a linear (typed 1D) texture fetch. 

154  

155 Parameters 

156 ---------- 

157 buffer : Buffer 

158 Device-memory backing. Must remain alive for the lifetime of any 

159 :class:`TextureObject` built from this descriptor. 

160 format : ArrayFormatType, str, or numpy.dtype 

161 Element format. Accepts an :class:`~cuda.core.typing.ArrayFormatType`, 

162 a plain string (e.g. ``"float32"``), or a NumPy dtype object. 

163 num_channels : int 

164 Channels per element. Must be 1, 2, or 4. 

165 size_bytes : int, optional 

166 Bytes of ``buffer`` to bind. Defaults to ``buffer.size``. Must not 

167 exceed it. 

168  

169 Notes 

170 ----- 

171 Texture objects built from a linear resource ignore the 

172 :class:`TextureObjectOptions` addressing/filtering fields — kernels read 

173 through a typed 1D fetch with bounds checking only. 

174 """ 

175 if not isinstance(buffer, Buffer): 1pIJyECqlb

176 raise TypeError(f"buffer must be a Buffer, got {type(buffer).__name__}") 1J

177 fmt = _validate_format_channels(format, num_channels) 1pIyECqlb

178 cu_format = _ARRAYFORMAT_TO_CU[fmt] 1pyECqlb

179  

180 buf_size = int(buffer.size) 1pyECqlb

181 elem = _FORMAT_ELEM_SIZE[cu_format] * int(num_channels) 1pyECqlb

182 if size_bytes is None: 1pyECqlb

183 size = buf_size 1plb

184 else: 

185 size = int(size_bytes) 1yECq

186 if size > buf_size: 1yECq

187 raise ValueError( 1E

188 f"size_bytes ({size}) exceeds buffer.size ({buf_size})" 1E

189 ) 

190 if size < elem: 1pyCqlb

191 raise ValueError( 1C

192 f"size_bytes ({size}) must be at least one element ({elem} bytes)" 1C

193 ) 

194 if size % elem != 0: 1pyqlb

195 raise ValueError( 1y

196 f"size_bytes ({size}) must be a multiple of element size " 1y

197 f"({elem} bytes for {fmt.name} x {num_channels})" 1y

198 ) 

199  

200 self = cls.__new__(cls) 1pqlb

201 self._kind = "linear" 1pqlb

202 self._source = buffer 1pqlb

203 self._format = cu_format 1pqlb

204 self._num_channels = int(num_channels) 1pqlb

205 self._size_bytes = size 1pqlb

206 self._width = None 1pqlb

207 self._height = None 1pqlb

208 self._pitch_bytes = None 1pqlb

209 return self 1pqlb

210  

211 @classmethod 

212 def from_pitch2d( 

213 cls, buffer, *, format, num_channels, width, height, pitch_bytes 

214 ): 

215 """Build a resource descriptor for a row-pitched 2D image. 

216  

217 Parameters 

218 ---------- 

219 buffer : Buffer 

220 Device-memory backing. Must remain alive for the lifetime of any 

221 :class:`TextureObject` built from this descriptor. 

222 format : ArrayFormatType, str, or numpy.dtype 

223 Element format. Accepts an :class:`~cuda.core.typing.ArrayFormatType`, 

224 a plain string (e.g. ``"float32"``), or a NumPy dtype object. 

225 num_channels : int 

226 Channels per element. Must be 1, 2, or 4. 

227 width : int 

228 Image width, in elements. 

229 height : int 

230 Image height, in rows. 

231 pitch_bytes : int 

232 Distance between consecutive rows, in bytes. Must be at least 

233 ``width * format_size * num_channels`` and meet the driver's 

234 ``CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT``. 

235 """ 

236 if not isinstance(buffer, Buffer): 1KLMFszla

237 raise TypeError(f"buffer must be a Buffer, got {type(buffer).__name__}") 1M

238 fmt = _validate_format_channels(format, num_channels) 1KLFszla

239 cu_format = _ARRAYFORMAT_TO_CU[fmt] 1Fszla

240  

241 w = int(width) 1Fszla

242 h = int(height) 1Fszla

243 p = int(pitch_bytes) 1Fszla

244 if w < 1: 1Fszla

245 raise ValueError(f"width must be >= 1, got {w}") 1F

246 if h < 1: 1Fszla

247 raise ValueError(f"height must be >= 1, got {h}") 1F

248 elem = _FORMAT_ELEM_SIZE[cu_format] * int(num_channels) 1szla

249 min_pitch = w * elem 1szla

250 if p < min_pitch: 1szla

251 raise ValueError( 1z

252 f"pitch_bytes ({p}) must be >= width * element_bytes ({min_pitch})" 1z

253 ) 

254 if p * h > int(buffer.size): 1sla

255 raise ValueError( 1s

256 f"pitch_bytes * height ({p * h}) exceeds buffer.size ({int(buffer.size)})" 1s

257 ) 

258  

259 self = cls.__new__(cls) 1la

260 self._kind = "pitch2d" 1la

261 self._source = buffer 1la

262 self._format = cu_format 1la

263 self._num_channels = int(num_channels) 1la

264 self._size_bytes = None 1la

265 self._width = w 1la

266 self._height = h 1la

267 self._pitch_bytes = p 1la

268 return self 1la

269  

270 @property 

271 def kind(self): 

272 return self._kind 1cmknopxuvlAwebdafijg

273  

274 @property 

275 def source(self): 

276 return self._source 1cmknopxuvwebdafijg

277  

278 @property 

279 def format(self): 

280 """The element :class:`~cuda.core.typing.ArrayFormatType` (``None`` for array-backed).""" 

281 return None if self._format is None else _CU_TO_ARRAYFORMAT[self._format] 1pa

282  

283 @property 

284 def num_channels(self): 

285 """Channels per element (``None`` for array-backed).""" 

286 return self._num_channels 1p

287  

288 @property 

289 def size_bytes(self): 

290 """Bytes bound for a linear resource (``None`` for other kinds).""" 

291 return self._size_bytes 

292  

293 @property 

294 def width(self): 

295 """Pitch2D image width, in elements (``None`` for other kinds).""" 

296 return self._width 

297  

298 @property 

299 def height(self): 

300 """Pitch2D image height, in rows (``None`` for other kinds).""" 

301 return self._height 

302  

303 @property 

304 def pitch_bytes(self): 

305 """Pitch2D row pitch, in bytes (``None`` for other kinds).""" 

306 return self._pitch_bytes 

307  

308 def __repr__(self): 

309 if self._kind == "linear": 1pa

310 return ( 1p

311 f"ResourceDescriptor(kind='linear', format={self.format.name}, " 1p

312 f"num_channels={self._num_channels}, size_bytes={self._size_bytes})" 1p

313 ) 

314 if self._kind == "pitch2d": 1a

315 return ( 1a

316 f"ResourceDescriptor(kind='pitch2d', format={self.format.name}, " 1a

317 f"num_channels={self._num_channels}, " 1a

318 f"width={self._width}, height={self._height}, " 1a

319 f"pitch_bytes={self._pitch_bytes})" 1a

320 ) 

321 return f"ResourceDescriptor(kind={self._kind!r})" 

322  

323  

324@dataclass 

325class TextureObjectOptions: 

326 """Sampling state for a :class:`TextureObject` (mirrors ``CUDA_TEXTURE_DESC``). 

327  

328 Attributes 

329 ---------- 

330 address_mode : AddressModeType or tuple of AddressModeType 

331 Boundary behavior per axis. May be a single 

332 :class:`~cuda.core.typing.AddressModeType` (applied to all axes) or a 

333 tuple of 1-3 entries (one per dimension). Plain strings are accepted. 

334 filter_mode : FilterModeType 

335 Texel sampling mode. Default ``POINT``. Plain strings are accepted. 

336 read_mode : ReadModeType 

337 How sampled integer values are returned. Default ``ELEMENT_TYPE``. 

338 Plain strings are accepted. 

339 normalized_coords : bool 

340 If True, coordinates are in ``[0, 1]`` instead of pixel indices. 

341 srgb : bool 

342 If True, perform sRGB → linear conversion on read (8-bit formats only). 

343 disable_trilinear_optimization : bool 

344 If True, request exact trilinear filtering. 

345 seamless_cubemap : bool 

346 If True, enable seamless cubemap edge filtering. 

347 max_anisotropy : int 

348 Maximum anisotropy; 0 disables anisotropic filtering. 

349 mipmap_filter_mode : FilterModeType 

350 Filtering between mipmap levels. Default ``POINT``. Plain strings are 

351 accepted. 

352 mipmap_level_bias : float 

353 min_mipmap_level_clamp : float 

354 max_mipmap_level_clamp : float 

355 border_color : tuple of float or None 

356 4-tuple used when ``address_mode`` includes ``BORDER``; ``None`` means 

357 zero. 

358  

359 .. versionadded:: 1.1.0 

360 """ 

361  

362 address_mode: AddressModeType | str | tuple[AddressModeType | str, ...] = AddressModeType.CLAMP 

363 filter_mode: FilterModeType | str = FilterModeType.POINT 

364 read_mode: ReadModeType | str = ReadModeType.ELEMENT_TYPE 

365 normalized_coords: bool = False 

366 srgb: bool = False 

367 disable_trilinear_optimization: bool = False 

368 seamless_cubemap: bool = False 

369 max_anisotropy: int = 0 

370 mipmap_filter_mode: FilterModeType | str = FilterModeType.POINT 

371 mipmap_level_bias: float = 0.0 

372 min_mipmap_level_clamp: float = 0.0 

373 max_mipmap_level_clamp: float = 0.0 

374 border_color: tuple[float, ...] | None = None 

375  

376 def __post_init__(self): 

377 self.filter_mode = _normalize_enum("filter_mode", self.filter_mode, FilterModeType) 1cmknoebdafiGtBjDg

378 self.read_mode = _normalize_enum("read_mode", self.read_mode, ReadModeType) 1cmknoebdafitBjDg

379 self.mipmap_filter_mode = _normalize_enum( 1cmknoebdafitjDg

380 "mipmap_filter_mode", self.mipmap_filter_mode, FilterModeType 1cmknoebdafitjDg

381 ) 

382  

383  

384def _normalize_address_modes(address_mode): 

385 """Return a 3-tuple of :class:`AddressModeType` values from a scalar or 

386 1-3 tuple. Individual entries may be plain strings.""" 

387 if isinstance(address_mode, (AddressModeType, str)): 1cmknoebdafijg

388 m = _normalize_enum("address_mode", address_mode, AddressModeType) 1cebdafijg

389 return (m, m, m) 1cebdafijg

390 try: 1cmkno

391 modes = tuple(address_mode) 1cmkno

392 except TypeError as e: 1n

393 raise TypeError( 1n

394 "address_mode must be an AddressModeType or a tuple of AddressModeType" 

395 ) from e 1n

396 if not 1 <= len(modes) <= 3: 1cmko

397 raise ValueError( 1mo

398 f"address_mode tuple must have 1-3 entries, got {len(modes)}" 1mo

399 ) 

400 modes = tuple( 1ck

401 _normalize_enum(f"address_mode[{i}]", m, AddressModeType) 1ck

402 for i, m in enumerate(modes) 1ck

403 ) 

404 # Pad to 3 entries by repeating the last one. 

405 padded = list(modes) + [modes[-1]] * (3 - len(modes)) 1c

406 return tuple(padded) 1c

407  

408  

409cdef class TextureObject: 

410 """A bindless texture handle for kernel-side sampled reads. 

411  

412 Wraps ``cuTexObjectCreate``. The underlying memory resource (e.g. the 

413 :class:`OpaqueArray` referenced by the descriptor) is kept alive for the 

414 lifetime of this object to prevent dangling handles. 

415  

416 Construct via :meth:`cuda.core.Device.create_texture_object`. Passes to 

417 kernels as a 64-bit handle (via the ``handle`` property). 

418  

419 .. versionadded:: 1.1.0 

420 """ 

421  

422 def __init__(self, *args, **kwargs): 

423 raise RuntimeError( 1O

424 "TextureObject cannot be instantiated directly. " 

425 "Use Device.create_texture_object()." 

426 ) 

427  

428 @property 

429 def handle(self): 

430 """The underlying ``CUtexObject`` as an integer (64-bit kernel arg).""" 

431 return as_intptr(self._handle) 1cebdafg

432  

433 @property 

434 def resource(self): 

435 """The :class:`ResourceDescriptor` this texture was built from.""" 

436 return self._source_ref 1ebd

437  

438 @property 

439 def options(self): 

440 """The :class:`TextureObjectOptions` this texture was built from.""" 

441 return self._options 1e

442  

443 @property 

444 def device(self): 

445 from cuda.core._device import Device 

446 return Device(self._device_id) 

447  

448 cpdef close(self): 

449 """Release this object's reference to the underlying ``CUtexObject``. 

450  

451 Destruction (``cuTexObjectDestroy``) and release of the backing resource 

452 happen via the handle's deleter when the last reference is dropped. 

453 Idempotent. 

454 """ 

455 self._handle.reset() 1cebdafg

456 self._source_ref = None 1cebdafg

457  

458 def __enter__(self): 

459 return self 

460  

461 def __exit__(self, exc_type, exc, tb): 

462 self.close() 

463  

464 def __repr__(self): 

465 return f"TextureObject(handle=0x{as_intptr(self._handle):x})" 

466  

467  

468def _create_texture_object(resource, options): 

469 """Create a :class:`TextureObject` on the current device. 

470  

471 Backs :meth:`cuda.core.Device.create_texture_object`. ``resource`` is a 

472 :class:`ResourceDescriptor`; ``options`` is a :class:`TextureObjectOptions` 

473 (or a mapping accepted by it). 

474 """ 

475 if not isinstance(resource, ResourceDescriptor): 1cmknoebdafirjDg

476 raise TypeError( 1D

477 f"resource must be a ResourceDescriptor, got " 1D

478 f"{type(resource).__name__}" 1D

479 ) 

480 cdef object opts = check_or_create_options( 1cmknoebdafirjg

481 TextureObjectOptions, options, "Texture object options" 1cmknoebdafirjg

482 ) 

483  

484 cdef cydriver.CUDA_RESOURCE_DESC res_desc 

485 cdef cydriver.CUDA_TEXTURE_DESC tex_desc 

486 memset(&res_desc, 0, sizeof(res_desc)) 1cmknoebdafijg

487 memset(&tex_desc, 0, sizeof(tex_desc)) 1cmknoebdafijg

488  

489 # --- Resource descriptor --- 

490 cdef OpaqueArray arr 

491 cdef MipmappedArray mip 

492 cdef Buffer buf 

493 cdef intptr_t devptr 

494 if resource.kind == "array": 1cmknoebdafijg

495 arr = <OpaqueArray>resource.source 1cmknoefijg

496 res_desc.resType = cydriver.CU_RESOURCE_TYPE_ARRAY 1cmknoefijg

497 res_desc.res.array.hArray = as_cu(arr._handle) 1cmknoefijg

498 elif resource.kind == "mipmapped_array": 1bda

499 mip = <MipmappedArray>resource.source 1d

500 res_desc.resType = cydriver.CU_RESOURCE_TYPE_MIPMAPPED_ARRAY 1d

501 res_desc.res.mipmap.hMipmappedArray = as_cu(mip._handle) 1d

502 elif resource.kind == "linear": 1ba

503 buf = <Buffer>resource.source 1b

504 devptr = int(buf.handle) 1b

505 res_desc.resType = cydriver.CU_RESOURCE_TYPE_LINEAR 1b

506 res_desc.res.linear.devPtr = <cydriver.CUdeviceptr>devptr 1b

507 res_desc.res.linear.format = <cydriver.CUarray_format><int>resource._format 1b

508 res_desc.res.linear.numChannels = <unsigned int>resource._num_channels 1b

509 res_desc.res.linear.sizeInBytes = <size_t>resource._size_bytes 1b

510 elif resource.kind == "pitch2d": 1a

511 buf = <Buffer>resource.source 1a

512 devptr = int(buf.handle) 1a

513 res_desc.resType = cydriver.CU_RESOURCE_TYPE_PITCH2D 1a

514 res_desc.res.pitch2D.devPtr = <cydriver.CUdeviceptr>devptr 1a

515 res_desc.res.pitch2D.format = <cydriver.CUarray_format><int>resource._format 1a

516 res_desc.res.pitch2D.numChannels = <unsigned int>resource._num_channels 1a

517 res_desc.res.pitch2D.width = <size_t>resource._width 1a

518 res_desc.res.pitch2D.height = <size_t>resource._height 1a

519 res_desc.res.pitch2D.pitchInBytes = <size_t>resource._pitch_bytes 1a

520 else: 

521 raise NotImplementedError( 

522 f"ResourceDescriptor kind {resource.kind!r} is not yet supported" 

523 ) 

524  

525 # --- Texture descriptor --- 

526 # filter_mode/read_mode/mipmap_filter_mode are normalized to their 

527 # StrEnum types by TextureObjectOptions.__post_init__; address_mode is 

528 # normalized (and str-coerced) here. 

529 modes = _normalize_address_modes(opts.address_mode) 1cmknoebdafijg

530 tex_desc.addressMode[0] = <cydriver.CUaddress_mode>_ADDRESSMODE_TO_CU[modes[0]] 1cebdafijg

531 tex_desc.addressMode[1] = <cydriver.CUaddress_mode>_ADDRESSMODE_TO_CU[modes[1]] 1cebdafijg

532 tex_desc.addressMode[2] = <cydriver.CUaddress_mode>_ADDRESSMODE_TO_CU[modes[2]] 1cebdafijg

533  

534 tex_desc.filterMode = <cydriver.CUfilter_mode>_FILTERMODE_TO_CU[opts.filter_mode] 1cebdafijg

535  

536 cdef unsigned int flags = 0 1cebdafijg

537 # CU_TRSF_READ_AS_INTEGER suppresses normalization, so it maps to 

538 # ReadModeType.ELEMENT_TYPE. 

539 if opts.read_mode == ReadModeType.ELEMENT_TYPE: 1cebdafijg

540 flags |= _TRSF_READ_AS_INTEGER 1cebdafijg

541 if opts.normalized_coords: 1cebdafijg

542 flags |= _TRSF_NORMALIZED_COORDINATES 1ed

543 if opts.srgb: 1cebdafijg

544 flags |= _TRSF_SRGB 

545 if opts.disable_trilinear_optimization: 1cebdafijg

546 flags |= _TRSF_DISABLE_TRILINEAR_OPTIMIZATION 

547 if opts.seamless_cubemap: 1cebdafijg

548 flags |= _TRSF_SEAMLESS_CUBEMAP 

549 tex_desc.flags = flags 1cebdafijg

550  

551 if opts.max_anisotropy < 0: 1cebdafijg

552 raise ValueError("max_anisotropy must be >= 0") 1j

553 tex_desc.maxAnisotropy = <unsigned int>opts.max_anisotropy 1cebdafig

554  

555 tex_desc.mipmapFilterMode = <cydriver.CUfilter_mode>_FILTERMODE_TO_CU[opts.mipmap_filter_mode] 1cebdafig

556 tex_desc.mipmapLevelBias = <float>opts.mipmap_level_bias 1cebdafig

557 tex_desc.minMipmapLevelClamp = <float>opts.min_mipmap_level_clamp 1cebdafig

558 tex_desc.maxMipmapLevelClamp = <float>opts.max_mipmap_level_clamp 1cebdafig

559  

560 cdef int i 

561 if opts.border_color is None: 1cebdafig

562 for i in range(4): 1cebdafg

563 tex_desc.borderColor[i] = 0.0 1cebdafg

564 else: 

565 bc = tuple(opts.border_color) 1i

566 if len(bc) != 4: 1i

567 raise ValueError( 1i

568 f"border_color must have 4 elements, got {len(bc)}" 1i

569 ) 

570 for i in range(4): 

571 tex_desc.borderColor[i] = <float>bc[i] 

572  

573 cdef TexObjectHandle h 

574 if resource.kind == "array": 1cebdafg

575 h = create_tex_object_handle_array(res_desc, tex_desc, arr._handle) 1cefg

576 elif resource.kind == "mipmapped_array": 1bda

577 h = create_tex_object_handle_mipmap(res_desc, tex_desc, mip._handle) 1d

578 else: # linear or pitch2d — both backed by a device Buffer 

579 h = create_tex_object_handle_linear(res_desc, tex_desc, buf._h_ptr) 1ba

580 if not h: 1cebdafg

581 HANDLE_RETURN(get_last_error()) 

582  

583 cdef TextureObject self = TextureObject.__new__(TextureObject) 1cebdafg

584 self._handle = h 1cebdafg

585 self._source_ref = resource 1cebdafg

586 self._options = opts 1cebdafg

587 self._device_id = _get_current_device_id() 1cebdafg

588 return self 1cebdafg