compushady 1.0.0a1__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
compushady/__init__.py ADDED
@@ -0,0 +1,1008 @@
1
+ import functools
2
+ import importlib
3
+ from . import config
4
+ import atexit
5
+ import os
6
+
7
+ HEAP_DEFAULT = 0
8
+ HEAP_UPLOAD = 1
9
+ HEAP_READBACK = 2
10
+
11
+ SHADER_BINARY_TYPE_DXIL = 0
12
+ SHADER_BINARY_TYPE_SPIRV = 1
13
+ SHADER_BINARY_TYPE_DXBC = 2
14
+ SHADER_BINARY_TYPE_MSL = 3
15
+ SHADER_BINARY_TYPE_GLSL = 4
16
+ SHADER_BINARY_TYPE_WGSL = 5
17
+
18
+ SAMPLER_FILTER_POINT = 0
19
+ SAMPLER_FILTER_LINEAR = 1
20
+
21
+ SAMPLER_ADDRESS_MODE_WRAP = 0
22
+ SAMPLER_ADDRESS_MODE_MIRROR = 1
23
+ SAMPLER_ADDRESS_MODE_CLAMP = 2
24
+
25
+
26
+ class UnknownBackend(Exception):
27
+ pass
28
+
29
+
30
+ class BufferException(Exception):
31
+ pass
32
+
33
+
34
+ class Texture1DException(Exception):
35
+ pass
36
+
37
+
38
+ class Texture2DException(Exception):
39
+ pass
40
+
41
+
42
+ class Texture3DException(Exception):
43
+ pass
44
+
45
+
46
+ class SamplerException(Exception):
47
+ pass
48
+
49
+
50
+ class HeapException(Exception):
51
+ pass
52
+
53
+
54
+ _backend = None
55
+
56
+
57
+ def available_backends():
58
+ """Names of the backends compiled into this build."""
59
+ from compushady._native import available_backends as _available
60
+
61
+ return _available()
62
+
63
+ _discovered_devices = None
64
+ _current_device = None
65
+
66
+
67
+ def get_backend():
68
+ def debug_callback():
69
+ messages = get_current_device().get_debug_messages()
70
+ for message in messages:
71
+ print(message)
72
+
73
+ global _backend
74
+ if _backend is None:
75
+ try:
76
+ _backend = importlib.import_module(
77
+ "compushady.backends.{0}".format(config.wanted_backend)
78
+ )
79
+ except ImportError:
80
+ raise UnknownBackend(
81
+ "backend '{0}' is not available (available: {1})".format(
82
+ config.wanted_backend, ", ".join(available_backends())
83
+ )
84
+ )
85
+ if config.debug:
86
+ _backend.enable_debug()
87
+ atexit.register(debug_callback)
88
+ return _backend
89
+
90
+
91
+ def get_discovered_devices():
92
+ global _discovered_devices
93
+ if _discovered_devices is None:
94
+ _discovered_devices = get_backend().get_discovered_devices()
95
+ return _discovered_devices
96
+
97
+
98
+ def set_current_device(index):
99
+ global _current_device
100
+ _current_device = get_discovered_devices()[index]
101
+
102
+
103
+ def get_current_device():
104
+ global _current_device
105
+ if _current_device is None:
106
+ _current_device = get_best_device()
107
+ return _current_device
108
+
109
+
110
+ def get_best_device():
111
+ if "COMPUSHADY_DEVICE" in os.environ:
112
+ return get_discovered_devices()[int(os.environ["COMPUSHADY_DEVICE"])]
113
+ return sorted(
114
+ get_discovered_devices(),
115
+ key=lambda x: (x.is_hardware, x.is_discrete, x.dedicated_video_memory),
116
+ )[-1]
117
+
118
+
119
+ class Resource:
120
+ def copy_to(
121
+ self,
122
+ destination,
123
+ size=0,
124
+ src_offset=0,
125
+ dst_offset=0,
126
+ width=0,
127
+ height=0,
128
+ depth=0,
129
+ src_x=0,
130
+ src_y=0,
131
+ src_z=0,
132
+ dst_x=0,
133
+ dst_y=0,
134
+ dst_z=0,
135
+ src_slice=0,
136
+ dst_slice=0,
137
+ src_mip=0,
138
+ dst_mip=0,
139
+ ):
140
+ self.handle.copy_to(
141
+ destination.handle,
142
+ size,
143
+ src_offset,
144
+ dst_offset,
145
+ width,
146
+ height,
147
+ depth,
148
+ src_x,
149
+ src_y,
150
+ src_z,
151
+ dst_x,
152
+ dst_y,
153
+ dst_z,
154
+ src_slice,
155
+ dst_slice,
156
+ src_mip,
157
+ dst_mip,
158
+ )
159
+
160
+ def copy_to_submit(self, destination, **kwargs):
161
+ """Queue ``copy_to`` without waiting; returns a ``Fence``."""
162
+ return self.handle.copy_to_submit(destination.handle, **kwargs)
163
+
164
+ async def copy_to_async(self, destination, **kwargs):
165
+ """``copy_to`` as an asyncio coroutine."""
166
+ await self.copy_to_submit(destination, **kwargs)
167
+
168
+ @property
169
+ def size(self):
170
+ return self.handle.size
171
+
172
+ @property
173
+ def heap_size(self):
174
+ return self.handle.heap_size
175
+
176
+ def bind_tile(
177
+ self,
178
+ x,
179
+ y,
180
+ z,
181
+ heap,
182
+ heap_offset=0,
183
+ slice=0,
184
+ ):
185
+ self.handle.bind_tile(
186
+ x, y, z, heap.handle if heap else None, heap_offset, slice
187
+ )
188
+
189
+ @property
190
+ def mips(self):
191
+ return self.handle.mips
192
+
193
+ def get_mip_row_pitch(self, mip):
194
+ """Row pitch of mip level ``mip`` in a buffer (``copy_to`` with ``src_mip``/``dst_mip``)."""
195
+ return self.handle.mip_layout(mip)[0]
196
+
197
+ def get_mip_size(self, mip):
198
+ """Bytes of mip level ``mip`` (of one slice) in a buffer."""
199
+ return self.handle.mip_layout(mip)[1]
200
+
201
+ def mip_view(self, mip):
202
+ """A view of mip level ``mip`` to bind as SRV, UAV or render target (for example to
203
+ generate the chain with a compute shader). Views cannot be copied."""
204
+ view = self.__class__.__new__(self.__class__)
205
+ view.device = getattr(self, "device", None)
206
+ view.heap = None
207
+ view.handle = self.handle.mip_view(mip)
208
+ view._parent = self
209
+ return view
210
+
211
+ def bind_tiles(self, tiles):
212
+ """Map (or unmap) many tiles in one queue operation and wait: ``tiles`` is a list of
213
+ ``(x, y, z, heap)`` or ``(x, y, z, heap, heap_offset, slice)``, heap None to unmap."""
214
+ self.handle.bind_tiles(self._tiles(tiles))
215
+
216
+ def bind_tiles_submit(self, tiles):
217
+ """``bind_tiles`` without waiting; returns a ``Fence``. Work submitted later is ordered
218
+ after the mappings."""
219
+ return self.handle.bind_tiles(self._tiles(tiles), submit=True)
220
+
221
+ async def bind_tiles_async(self, tiles):
222
+ await self.bind_tiles_submit(tiles)
223
+
224
+ @staticmethod
225
+ def _tiles(tiles):
226
+ out = []
227
+ for t in tiles:
228
+ t = tuple(t) + (0, 0)[max(0, len(t) - 4) :]
229
+ x, y, z, heap, heap_offset, slice = t[:6]
230
+ out.append((x, y, z, heap.handle if heap is not None else None, heap_offset, slice))
231
+ return out
232
+
233
+ @property
234
+ def tiles_x(self):
235
+ return self.handle.tiles_x
236
+
237
+ @property
238
+ def tiles_y(self):
239
+ return self.handle.tiles_y
240
+
241
+ @property
242
+ def tiles_z(self):
243
+ return self.handle.tiles_z
244
+
245
+ @property
246
+ def tile_width(self):
247
+ return self.handle.tile_width
248
+
249
+ @property
250
+ def tile_height(self):
251
+ return self.handle.tile_height
252
+
253
+ @property
254
+ def tile_depth(self):
255
+ return self.handle.tile_depth
256
+
257
+
258
+ class Buffer(Resource):
259
+ def __init__(
260
+ self,
261
+ size,
262
+ heap_type=HEAP_DEFAULT,
263
+ stride=0,
264
+ format=0,
265
+ heap=None,
266
+ heap_offset=0,
267
+ sparse=False,
268
+ device=None,
269
+ ):
270
+ self.device = device if device else get_current_device()
271
+ self.heap = heap
272
+ self.handle = self.device.create_buffer(
273
+ heap_type,
274
+ size,
275
+ stride,
276
+ format,
277
+ heap.handle if heap else None,
278
+ heap_offset,
279
+ sparse,
280
+ )
281
+
282
+ def upload(self, data, offset=0):
283
+ self.handle.upload(data, offset)
284
+
285
+ def upload2d(self, data, pitch, width, height, bytes_per_pixel):
286
+ return self.handle.upload2d(data, pitch, width, height, bytes_per_pixel)
287
+
288
+ def upload_chunked(self, data, stride, filler):
289
+ return self.handle.upload_chunked(data, stride, filler)
290
+
291
+ def readback(self, buffer_or_size=0, offset=0):
292
+ if isinstance(buffer_or_size, int):
293
+ return self.handle.readback(buffer_or_size, offset)
294
+ self.handle.readback_to_buffer(buffer_or_size, offset)
295
+
296
+ def readback2d(self, pitch, width, height, bytes_per_pixel):
297
+ return self.handle.readback2d(pitch, width, height, bytes_per_pixel)
298
+
299
+
300
+ class Texture1D(Resource):
301
+ def __init__(
302
+ self,
303
+ width,
304
+ format,
305
+ heap=None,
306
+ heap_offset=0,
307
+ slices=1,
308
+ sparse=False,
309
+ device=None,
310
+ mips=1,
311
+ ):
312
+ self.device = device if device else get_current_device()
313
+ self.heap = heap
314
+ if mips == 0:
315
+ mips = width.bit_length()
316
+ self.handle = self.device.create_texture1d(
317
+ width, format, heap.handle if heap else None, heap_offset, slices, sparse, mips
318
+ )
319
+
320
+ @property
321
+ def width(self):
322
+ return self.handle.width
323
+
324
+ @property
325
+ def slices(self):
326
+ return self.handle.slices
327
+
328
+ @property
329
+ def row_pitch(self):
330
+ return self.handle.row_pitch
331
+
332
+
333
+ class Texture2D(Resource):
334
+ def __init__(
335
+ self,
336
+ width,
337
+ height,
338
+ format,
339
+ heap=None,
340
+ heap_offset=0,
341
+ slices=1,
342
+ sparse=False,
343
+ device=None,
344
+ mips=1,
345
+ ):
346
+ """``mips``: mip levels (0 for the whole chain down to 1x1)."""
347
+ self.device = device if device else get_current_device()
348
+ self.heap = heap
349
+ if mips == 0:
350
+ mips = max(width, height).bit_length()
351
+ self.handle = self.device.create_texture2d(
352
+ width,
353
+ height,
354
+ format,
355
+ heap.handle if heap else None,
356
+ heap_offset,
357
+ slices,
358
+ sparse,
359
+ mips,
360
+ )
361
+
362
+ @property
363
+ def width(self):
364
+ return self.handle.width
365
+
366
+ @property
367
+ def height(self):
368
+ return self.handle.height
369
+
370
+ @property
371
+ def slices(self):
372
+ return self.handle.slices
373
+
374
+ @property
375
+ def row_pitch(self):
376
+ return self.handle.row_pitch
377
+
378
+
379
+ class Texture3D(Resource):
380
+ def __init__(
381
+ self,
382
+ width,
383
+ height,
384
+ depth,
385
+ format,
386
+ heap=None,
387
+ heap_offset=0,
388
+ sparse=False,
389
+ device=None,
390
+ mips=1,
391
+ ):
392
+ self.device = device if device else get_current_device()
393
+ self.heap = heap
394
+ if mips == 0:
395
+ mips = max(width, height, depth).bit_length()
396
+ self.handle = self.device.create_texture3d(
397
+ width,
398
+ height,
399
+ depth,
400
+ format,
401
+ heap.handle if heap else None,
402
+ heap_offset,
403
+ sparse,
404
+ mips,
405
+ )
406
+
407
+ @property
408
+ def width(self):
409
+ return self.handle.width
410
+
411
+ @property
412
+ def height(self):
413
+ return self.handle.height
414
+
415
+ @property
416
+ def depth(self):
417
+ return self.handle.depth
418
+
419
+ @property
420
+ def row_pitch(self):
421
+ return self.handle.row_pitch
422
+
423
+
424
+ class Swapchain:
425
+ def __init__(
426
+ self, window_handle, format, num_buffers=3, device=None, width=0, height=0
427
+ ):
428
+ self.device = device if device else get_current_device()
429
+ self.handle = self.device.create_swapchain(
430
+ window_handle, format, num_buffers, width, height
431
+ )
432
+
433
+ @property
434
+ def width(self):
435
+ return self.handle.width
436
+
437
+ @property
438
+ def height(self):
439
+ return self.handle.height
440
+
441
+ def present(self, resource, x=0, y=0):
442
+ self.handle.present(resource.handle, x, y)
443
+
444
+
445
+ class Sampler:
446
+ def __init__(
447
+ self,
448
+ address_mode_u=SAMPLER_ADDRESS_MODE_WRAP,
449
+ address_mode_v=SAMPLER_ADDRESS_MODE_WRAP,
450
+ address_mode_w=SAMPLER_ADDRESS_MODE_WRAP,
451
+ filter_min=SAMPLER_FILTER_POINT,
452
+ filter_mag=SAMPLER_FILTER_POINT,
453
+ device=None,
454
+ ):
455
+ self.device = device if device else get_current_device()
456
+ self.handle = self.device.create_sampler(
457
+ address_mode_u, address_mode_v, address_mode_w, filter_min, filter_mag
458
+ )
459
+
460
+
461
+ class Heap:
462
+ def __init__(self, heap_type, size, device=None):
463
+ self.device = device if device else get_current_device()
464
+ self.handle = self.device.create_heap(heap_type, size)
465
+
466
+ @property
467
+ def size(self):
468
+ return self.handle.size
469
+
470
+ @property
471
+ def heap_type(self):
472
+ return self.handle.heap_type
473
+
474
+
475
+ _CLASS_LETTERS = {"cbv": "b", "srv": "t", "uav": "u", "sampler": "s"}
476
+
477
+
478
+ def _reflection(shader):
479
+ from compushady._native import reflect
480
+
481
+ reflection = getattr(shader, "reflection", None)
482
+ return dict(reflection) if reflection is not None else reflect(shader)
483
+
484
+
485
+ def _resolve_bindings(shaders, bindings, cbv, srv, uav, samplers):
486
+ """``bindings`` ({name: resource or sampler}) to slot lists, using the shaders' reflection.
487
+
488
+ Returns ``(cbv, srv, uav, samplers, names)``; with no ``bindings`` the lists are returned
489
+ as given and ``names`` is None."""
490
+ if not bindings:
491
+ return cbv, srv, uav, samplers, None
492
+ if cbv or srv or uav or samplers:
493
+ raise ValueError("give resources either by name (bindings) or by slot (cbv, srv, uav, samplers), not both")
494
+ names = {}
495
+ for shader in shaders:
496
+ for name, binding in _reflection(shader).items():
497
+ if name in names and names[name] != binding:
498
+ raise ValueError(
499
+ "'{0}' is {1}{2} in one stage and {3}{4} in another".format(
500
+ name, _CLASS_LETTERS[names[name][0]], names[name][1], _CLASS_LETTERS[binding[0]], binding[1]
501
+ )
502
+ )
503
+ names[name] = binding
504
+ slots = {"cbv": {}, "srv": {}, "uav": {}, "sampler": {}}
505
+ for name, item in bindings.items():
506
+ if name not in names:
507
+ raise ValueError(
508
+ "the shader has no resource called '{0}' (unused resources are removed by the compiler; known: {1})".format(
509
+ name, ", ".join(sorted(names))
510
+ )
511
+ )
512
+ cls, slot = names[name]
513
+ if (cls == "sampler") != isinstance(item, Sampler):
514
+ raise ValueError(
515
+ "'{0}' is {1}{2}: pass a {3}".format(name, _CLASS_LETTERS[cls], slot, "Sampler" if cls == "sampler" else "resource")
516
+ )
517
+ slots[cls][slot] = item
518
+ lists = {}
519
+ for cls, by_slot in slots.items():
520
+ missing = [s for s in range(max(by_slot) + 1) if s not in by_slot] if by_slot else []
521
+ if missing:
522
+ labels = []
523
+ for s in missing:
524
+ owner = [n for n, b in names.items() if b == (cls, s)]
525
+ labels.append("{0}{1}{2}".format(_CLASS_LETTERS[cls], s, " ('{0}')".format(owner[0]) if owner else ""))
526
+ raise ValueError("no resource for " + ", ".join(labels))
527
+ lists[cls] = [by_slot[s] for s in sorted(by_slot)]
528
+ return lists["cbv"], lists["srv"], lists["uav"], lists["sampler"], names
529
+
530
+
531
+ class _NamedBind:
532
+ """``bind(name, resource)`` for pipelines created with named ``bindings``."""
533
+
534
+ _names = None
535
+
536
+ def bind(self, name, resource):
537
+ if self._names is None:
538
+ raise ValueError("rebinding by name needs a pipeline created with bindings={...}")
539
+ if name not in self._names:
540
+ raise ValueError("the shader has no resource called '{0}'".format(name))
541
+ cls, slot = self._names[name]
542
+ if cls == "sampler":
543
+ raise ValueError("'{0}' is a sampler: samplers cannot be rebound".format(name))
544
+ getattr(self, "bind_" + cls)(slot, resource)
545
+
546
+
547
+ class DescriptorHeap:
548
+ """An application-owned descriptor heap (modern bindless): resources and samplers are
549
+ registered once and get a stable index; every pipeline created with ``heap=`` reads them
550
+ from HLSL (Shader Model 6.6) with ``ResourceDescriptorHeap[i]`` / ``SamplerDescriptorHeap[i]``,
551
+ indices passed in push constants or buffers.
552
+
553
+ ``remove`` keeps an index (and its resource) reserved until the GPU work submitted with the
554
+ heap so far has completed; ``set_*`` overwrite an index in place after waiting for that work
555
+ (add a new entry and remove the old one to swap without stalling)."""
556
+
557
+ def __init__(self, resources=65536, samplers=256, device=None):
558
+ self.device = device if device else get_current_device()
559
+ self.handle = self.device.create_descriptor_heap(resources, samplers)
560
+
561
+ def add_cbv(self, resource):
562
+ return self.handle.add(0, resource.handle)
563
+
564
+ def add_srv(self, resource):
565
+ return self.handle.add(1, resource.handle)
566
+
567
+ def add_uav(self, resource):
568
+ return self.handle.add(2, resource.handle)
569
+
570
+ def add_sampler(self, sampler):
571
+ return self.handle.add_sampler(sampler.handle)
572
+
573
+ def set_cbv(self, index, resource):
574
+ self.handle.set(index, 0, resource.handle)
575
+
576
+ def set_srv(self, index, resource):
577
+ self.handle.set(index, 1, resource.handle)
578
+
579
+ def set_uav(self, index, resource):
580
+ self.handle.set(index, 2, resource.handle)
581
+
582
+ def set_sampler(self, index, sampler):
583
+ self.handle.set_sampler(index, sampler.handle)
584
+
585
+ def remove(self, index):
586
+ self.handle.remove(index)
587
+
588
+ def remove_sampler(self, index):
589
+ self.handle.remove(index, sampler=True)
590
+
591
+ @property
592
+ def resources(self):
593
+ """Resource indices in use."""
594
+ return self.handle.info()[0]
595
+
596
+ @property
597
+ def samplers(self):
598
+ """Sampler indices in use."""
599
+ return self.handle.info()[1]
600
+
601
+ @property
602
+ def capacity(self):
603
+ """(resource descriptors, sampler descriptors)."""
604
+ info = self.handle.info()
605
+ return info[2], info[3]
606
+
607
+
608
+ class Compute(_NamedBind):
609
+ def __init__(
610
+ self,
611
+ shader,
612
+ cbv=[],
613
+ srv=[],
614
+ uav=[],
615
+ samplers=[],
616
+ push_size=0,
617
+ bindless=False,
618
+ max_bindless=64,
619
+ device=None,
620
+ bindings=None,
621
+ heap=None,
622
+ ):
623
+ """``bindings``: resources and samplers by name ({"name": resource}), instead of
624
+ ``cbv``/``srv``/``uav``/``samplers`` by slot. ``heap``: a ``DescriptorHeap`` the shader
625
+ reads every resource from (then no slots, names or bindless)."""
626
+ cbv, srv, uav, samplers, self._names = _resolve_bindings([shader], bindings, cbv, srv, uav, samplers)
627
+ self.device = device if device else get_current_device()
628
+ self.handle = self.device.create_compute(
629
+ shader,
630
+ cbv=[resource.handle for resource in cbv],
631
+ srv=[resource.handle for resource in srv],
632
+ uav=[resource.handle for resource in uav],
633
+ samplers=[sampler.handle for sampler in samplers],
634
+ push_size=push_size,
635
+ bindless=max_bindless if bindless else 0,
636
+ heap=heap.handle if heap is not None else None,
637
+ )
638
+
639
+ def dispatch(self, x, y, z, push=None):
640
+ self.handle.dispatch(x, y, z, push if push else b"")
641
+
642
+ def dispatch_indirect(self, indirect_buffer, offset=0, push=None):
643
+ self.handle.dispatch_indirect(
644
+ indirect_buffer.handle, offset, push if push else b""
645
+ )
646
+
647
+ def dispatch_submit(self, x, y, z, push=None):
648
+ """Queue ``dispatch`` without waiting; returns a ``Fence`` (``wait()``, ``done``, ``await``)."""
649
+ return self.handle.dispatch_submit(x, y, z, push if push is not None else b"")
650
+
651
+ async def dispatch_async(self, x, y, z, push=None):
652
+ """``dispatch`` as an asyncio coroutine."""
653
+ await self.dispatch_submit(x, y, z, push)
654
+
655
+ def dispatch_indirect_submit(self, indirect_buffer, offset=0, push=None):
656
+ return self.handle.dispatch_indirect_submit(indirect_buffer.handle, offset, push if push is not None else b"")
657
+
658
+ async def dispatch_indirect_async(self, indirect_buffer, offset=0, push=None):
659
+ await self.dispatch_indirect_submit(indirect_buffer, offset, push)
660
+
661
+ def bind_cbv(self, index, cbv):
662
+ self.handle.bind_cbv(index, cbv.handle)
663
+
664
+ def bind_srv(self, index, srv):
665
+ self.handle.bind_srv(index, srv.handle)
666
+
667
+ def bind_uav(self, index, uav):
668
+ self.handle.bind_uav(index, uav.handle)
669
+
670
+
671
+ from compushady._native import Fence # noqa: E402,F401 (completion of *_submit work)
672
+
673
+
674
+ class Rasterizer(_NamedBind):
675
+ """A graphics pipeline (the ``rasterizer2`` API): a vertex and a pixel shader drawing
676
+ triangle lists into ``rtv`` (2D textures of the same size) and an optional ``dsv``
677
+ (a ``D32_FLOAT`` texture: depth test LESS, depth writes).
678
+
679
+ There is no vertex input: vertex shaders read their data from SRVs by ``SV_VertexID`` /
680
+ ``SV_InstanceID``. Back faces are culled (clockwise is front unless ``ccw``).
681
+
682
+ With ``ms`` (a mesh shader, ``ms_6_5``) instead of ``vs``, and optionally ``amplification``
683
+ (``as_6_5``), it is a mesh pipeline: draw it with ``dispatch_mesh``. Mesh pipelines need
684
+ D3D12 (mesh shader tier 1), Vulkan (VK_EXT_mesh_shader) or Metal 3, otherwise they raise
685
+ NotImplementedError; ``device.mesh_shader_limits`` is None then."""
686
+
687
+ def __init__(
688
+ self,
689
+ vs=b"",
690
+ ps=b"",
691
+ ms=b"",
692
+ rtv=[],
693
+ dsv=None,
694
+ cbv=[],
695
+ srv=[],
696
+ uav=[],
697
+ samplers=[],
698
+ wireframe=False,
699
+ ccw=False,
700
+ push_size=0,
701
+ bindless=False,
702
+ max_bindless=64,
703
+ device=None,
704
+ bindings=None,
705
+ amplification=b"",
706
+ heap=None,
707
+ ):
708
+ if ms and vs:
709
+ raise ValueError("a Rasterizer takes a vertex shader (vs) or a mesh shader (ms), not both")
710
+ if amplification and not ms:
711
+ raise ValueError("an amplification shader needs a mesh shader (ms)")
712
+ self.is_mesh = bool(ms)
713
+ stages = [amplification, ms, ps] if ms else [vs, ps]
714
+ cbv, srv, uav, samplers, self._names = _resolve_bindings([s for s in stages if s], bindings, cbv, srv, uav, samplers)
715
+ self.device = device if device else get_current_device()
716
+ if ms:
717
+ create = functools.partial(self.device.create_mesh_rasterizer, amplification or None, ms, ps)
718
+ else:
719
+ create = functools.partial(self.device.create_rasterizer, vs, ps)
720
+ self.handle = create(
721
+ rtv=[resource.handle for resource in rtv],
722
+ dsv=dsv.handle if dsv else None,
723
+ cbv=[resource.handle for resource in cbv],
724
+ srv=[resource.handle for resource in srv],
725
+ uav=[resource.handle for resource in uav],
726
+ samplers=[sampler.handle for sampler in samplers],
727
+ push_size=push_size,
728
+ wireframe=wireframe,
729
+ ccw=ccw,
730
+ bindless=max_bindless if bindless else 0,
731
+ heap=heap.handle if heap is not None else None,
732
+ )
733
+
734
+ def draw(self, num_vertices, num_instances=1, start_vertex=0, start_instance=0, push=None):
735
+ self.handle.draw(num_vertices, num_instances, start_vertex, start_instance, push if push is not None else b"")
736
+
737
+ def draw_submit(self, num_vertices, num_instances=1, start_vertex=0, start_instance=0, push=None):
738
+ """Queue ``draw`` without waiting; returns a ``Fence``."""
739
+ return self.handle.draw_submit(
740
+ num_vertices, num_instances, start_vertex, start_instance, push if push is not None else b""
741
+ )
742
+
743
+ async def draw_async(self, num_vertices, num_instances=1, start_vertex=0, start_instance=0, push=None):
744
+ await self.draw_submit(num_vertices, num_instances, start_vertex, start_instance, push)
745
+
746
+ def draw_indirect(self, indirect_buffer, offset=0, draw_count=1, stride=16, count_buffer=None, count_offset=0, push=None):
747
+ """Draw with arguments read from ``indirect_buffer`` at ``offset``: 4 uint32 per draw
748
+ (vertex count, instance count, first vertex, first instance), ``draw_count`` draws
749
+ ``stride`` bytes apart. With ``count_buffer`` the number of draws is the uint32 at
750
+ ``count_offset`` there (at most ``draw_count``; D3D12 and Vulkan only)."""
751
+ self.handle.draw_indirect(
752
+ indirect_buffer.handle,
753
+ offset,
754
+ draw_count,
755
+ stride,
756
+ count_buffer.handle if count_buffer is not None else None,
757
+ count_offset,
758
+ push if push is not None else b"",
759
+ )
760
+
761
+ def draw_indirect_submit(self, indirect_buffer, offset=0, draw_count=1, stride=16, count_buffer=None, count_offset=0, push=None):
762
+ """Queue ``draw_indirect`` without waiting; returns a ``Fence``."""
763
+ return self.handle.draw_indirect(
764
+ indirect_buffer.handle,
765
+ offset,
766
+ draw_count,
767
+ stride,
768
+ count_buffer.handle if count_buffer is not None else None,
769
+ count_offset,
770
+ push if push is not None else b"",
771
+ submit=True,
772
+ )
773
+
774
+ async def draw_indirect_async(self, indirect_buffer, offset=0, draw_count=1, stride=16, count_buffer=None, count_offset=0, push=None):
775
+ await self.draw_indirect_submit(indirect_buffer, offset, draw_count, stride, count_buffer, count_offset, push)
776
+
777
+ def dispatch_mesh(self, x=1, y=1, z=1, push=None):
778
+ """Run an ``x * y * z`` grid of amplification thread groups (or of mesh thread groups,
779
+ without an amplification shader)."""
780
+ self.handle.dispatch_mesh(x, y, z, push if push is not None else b"")
781
+
782
+ def dispatch_mesh_submit(self, x=1, y=1, z=1, push=None):
783
+ """Queue ``dispatch_mesh`` without waiting; returns a ``Fence``."""
784
+ return self.handle.dispatch_mesh(x, y, z, push if push is not None else b"", submit=True)
785
+
786
+ async def dispatch_mesh_async(self, x=1, y=1, z=1, push=None):
787
+ await self.dispatch_mesh_submit(x, y, z, push)
788
+
789
+ def dispatch_mesh_indirect(self, indirect_buffer, offset=0, draw_count=1, stride=12, count_buffer=None, count_offset=0, push=None):
790
+ """Mesh dispatches with thread group counts read from ``indirect_buffer`` at ``offset``:
791
+ 3 uint32 per dispatch (x, y, z), ``draw_count`` dispatches ``stride`` bytes apart. With
792
+ ``count_buffer`` the number is the uint32 at ``count_offset`` there (D3D12 and Vulkan only)."""
793
+ self.handle.dispatch_mesh_indirect(
794
+ indirect_buffer.handle,
795
+ offset,
796
+ draw_count,
797
+ stride,
798
+ count_buffer.handle if count_buffer is not None else None,
799
+ count_offset,
800
+ push if push is not None else b"",
801
+ )
802
+
803
+ def dispatch_mesh_indirect_submit(
804
+ self, indirect_buffer, offset=0, draw_count=1, stride=12, count_buffer=None, count_offset=0, push=None
805
+ ):
806
+ """Queue ``dispatch_mesh_indirect`` without waiting; returns a ``Fence``."""
807
+ return self.handle.dispatch_mesh_indirect(
808
+ indirect_buffer.handle,
809
+ offset,
810
+ draw_count,
811
+ stride,
812
+ count_buffer.handle if count_buffer is not None else None,
813
+ count_offset,
814
+ push if push is not None else b"",
815
+ submit=True,
816
+ )
817
+
818
+ async def dispatch_mesh_indirect_async(
819
+ self, indirect_buffer, offset=0, draw_count=1, stride=12, count_buffer=None, count_offset=0, push=None
820
+ ):
821
+ await self.dispatch_mesh_indirect_submit(indirect_buffer, offset, draw_count, stride, count_buffer, count_offset, push)
822
+
823
+ def clear(self, color=(0.0, 0.0, 0.0, 0.0)):
824
+ """Clear the render targets to ``color`` and the depth target to 1."""
825
+ self.handle.clear(color)
826
+
827
+ def clear_submit(self, color=(0.0, 0.0, 0.0, 0.0)):
828
+ return self.handle.clear_submit(color)
829
+
830
+ def bind_cbv(self, index, cbv):
831
+ self.handle.bind_cbv(index, cbv.handle)
832
+
833
+ def bind_srv(self, index, srv):
834
+ self.handle.bind_srv(index, srv.handle)
835
+
836
+ def bind_uav(self, index, uav):
837
+ self.handle.bind_uav(index, uav.handle)
838
+
839
+
840
+ # ---------------------------------------------------------------------------------------------
841
+ # Ray tracing (the API of the legacy ``raytracer`` branch, extended)
842
+
843
+ SHADER_TARGET_TYPE_CS = 0
844
+ SHADER_TARGET_TYPE_LIB = 1
845
+
846
+ IDENTITY = (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
847
+
848
+
849
+ class BLAS:
850
+ """Bottom level acceleration structure: triangles from a vertex buffer (3 floats at the
851
+ start of every ``vertex_stride`` bytes) and an optional uint32 index buffer, or, with
852
+ ``aabbs``, procedural boxes (6 floats: min xyz, max xyz)."""
853
+
854
+ def __init__(
855
+ self,
856
+ vertex_buffer=None,
857
+ index_buffer=None,
858
+ vertex_stride=None,
859
+ vertex_count=None,
860
+ index_count=None,
861
+ vertex_offset=0,
862
+ aabbs=None,
863
+ aabb_count=None,
864
+ aabb_stride=24,
865
+ device=None,
866
+ ):
867
+ self.device = device if device else get_current_device()
868
+ if aabbs is not None:
869
+ count = aabb_count if aabb_count is not None else aabbs.size // aabb_stride
870
+ self.handle = self.device.create_blas_aabbs(aabbs.handle, count, aabb_stride)
871
+ return
872
+ if vertex_stride is None:
873
+ vertex_stride = vertex_buffer.handle.stride or 12
874
+ if vertex_count is None:
875
+ vertex_count = (vertex_buffer.size - vertex_offset) // vertex_stride
876
+ if index_buffer is not None and index_count is None:
877
+ index_count = index_buffer.size // 4
878
+ self.handle = self.device.create_blas_triangles(
879
+ vertex_buffer.handle,
880
+ vertex_count,
881
+ vertex_stride,
882
+ vertex_offset,
883
+ index_buffer.handle if index_buffer is not None else None,
884
+ index_count or 0,
885
+ )
886
+
887
+
888
+ class TLASInstance:
889
+ """A BLAS placed in a TLAS: ``transform`` is a row-major 3x4 matrix (12 floats),
890
+ ``id`` is ``InstanceID()``, ``hit_group`` the offset of its hit groups in a RayTracer."""
891
+
892
+ def __init__(self, blas, transform=IDENTITY, id=0, mask=0xFF, hit_group=0):
893
+ self.blas = blas
894
+ self.transform = tuple(transform)
895
+ if len(self.transform) != 12:
896
+ raise ValueError("a TLAS instance transform is 12 floats (row-major 3x4)")
897
+ self.id = id
898
+ self.mask = mask
899
+ self.hit_group = hit_group
900
+
901
+
902
+ class TLAS(Resource):
903
+ """Top level acceleration structure, bound as an SRV (``RaytracingAccelerationStructure``).
904
+ ``instances`` is a BLAS, or a list of BLAS / TLASInstance."""
905
+
906
+ def __init__(self, instances=None, max_instances=None, device=None):
907
+ self.device = device if device else get_current_device()
908
+ instances = self._instances(instances)
909
+ if max_instances is None:
910
+ max_instances = max(len(instances), 1)
911
+ self.tlas = self.device.create_tlas(max_instances)
912
+ self.handle = self.tlas.resource()
913
+ if instances:
914
+ self.build(instances)
915
+
916
+ @staticmethod
917
+ def _instances(instances):
918
+ if instances is None:
919
+ return []
920
+ if isinstance(instances, (BLAS, TLASInstance)):
921
+ instances = [instances]
922
+ return [i if isinstance(i, TLASInstance) else TLASInstance(i) for i in instances]
923
+
924
+ def build(self, instances):
925
+ """Rebuild with new instances (no more than ``max_instances``)."""
926
+ self.tlas.build(
927
+ [(i.blas.handle, i.transform, i.id, i.mask, i.hit_group) for i in self._instances(instances)]
928
+ )
929
+
930
+
931
+ class HitGroup:
932
+ """Shaders run when a ray hits: a closest hit and/or any hit shader, plus an intersection
933
+ shader for procedural (AABB) geometry."""
934
+
935
+ def __init__(self, closest_hit=None, any_hit=None, intersection=None):
936
+ self.closest_hit = closest_hit
937
+ self.any_hit = any_hit
938
+ self.intersection = intersection
939
+
940
+
941
+ class RayTracer(_NamedBind):
942
+ """A ray tracing pipeline from a shader library (``hlsl.compile(source,
943
+ target_type=SHADER_TARGET_TYPE_LIB)``): ``raygen`` launched by ``dispatch_rays``,
944
+ ``miss`` shaders (``MissShaderIndex``), ``hit_groups`` (names of closest hit shaders or
945
+ HitGroup objects) and ``callable`` shaders (``CallShader`` index)."""
946
+
947
+ def __init__(
948
+ self,
949
+ shader,
950
+ cbv=[],
951
+ srv=[],
952
+ uav=[],
953
+ samplers=[],
954
+ raygen="main",
955
+ miss=[],
956
+ hit_groups=[],
957
+ callable=[],
958
+ max_payload_size=16,
959
+ max_attribute_size=8,
960
+ max_recursion=1,
961
+ push_size=0,
962
+ device=None,
963
+ bindings=None,
964
+ heap=None,
965
+ ):
966
+ cbv, srv, uav, samplers, self._names = _resolve_bindings([shader], bindings, cbv, srv, uav, samplers)
967
+ self.device = device if device else get_current_device()
968
+ groups = []
969
+ for g in hit_groups:
970
+ if isinstance(g, HitGroup):
971
+ groups.append((g.closest_hit, g.any_hit, g.intersection))
972
+ else:
973
+ groups.append((g, None, None))
974
+ self.handle = self.device.create_raytracer(
975
+ shader,
976
+ raygen=raygen,
977
+ miss=list(miss),
978
+ hit_groups=groups,
979
+ callable=list(callable),
980
+ max_payload_size=max_payload_size,
981
+ max_attribute_size=max_attribute_size,
982
+ max_recursion=max_recursion,
983
+ cbv=[resource.handle for resource in cbv],
984
+ srv=[resource.handle for resource in srv],
985
+ uav=[resource.handle for resource in uav],
986
+ samplers=[sampler.handle for sampler in samplers],
987
+ push_size=push_size,
988
+ heap=heap.handle if heap is not None else None,
989
+ )
990
+
991
+ def dispatch_rays(self, x, y, z, push=None):
992
+ self.handle.dispatch_rays(x, y, z, push if push else b"")
993
+
994
+ def dispatch_rays_submit(self, x, y, z, push=None):
995
+ """Queue ``dispatch_rays`` without waiting; returns a ``Fence``."""
996
+ return self.handle.dispatch_rays_submit(x, y, z, push if push is not None else b"")
997
+
998
+ async def dispatch_rays_async(self, x, y, z, push=None):
999
+ await self.dispatch_rays_submit(x, y, z, push)
1000
+
1001
+ def bind_cbv(self, index, cbv):
1002
+ self.handle.bind_cbv(index, cbv.handle)
1003
+
1004
+ def bind_srv(self, index, srv):
1005
+ self.handle.bind_srv(index, srv.handle)
1006
+
1007
+ def bind_uav(self, index, uav):
1008
+ self.handle.bind_uav(index, uav.handle)