rk_island/game/batch.py

56 lines
2.3 KiB
Python
Raw Normal View History

2022-08-28 05:09:52 +02:00
# Copyright (C) 2022 RozK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ctypes import c_ubyte, c_uint, c_void_p, addressof
2022-08-28 05:09:52 +02:00
from engine import (vec3, mat3, buffer,
INSTANCE_FLAG_SPAWNED, BATCH_MAX_SIZE, param_type, params_format, create_batch, draw_batch, destroy_batch)
2022-08-28 05:09:52 +02:00
class Batch:
2022-12-31 20:24:08 +01:00
__slots__ = '_batch', 'vertices', 'size', 'max_size', 'flags', 'meshes', 'params', '_params', '__dict__'
2022-08-28 05:09:52 +02:00
def __init__(self, vertices, max_size, max_meshes, **params_decls):
2022-08-28 05:09:52 +02:00
assert max_size <= BATCH_MAX_SIZE
nparams = len(params_decls)
names = params_decls.keys()
formats = params_decls.values()
2022-12-31 20:24:08 +01:00
self._batch = create_batch(vertices._vertices, max_size, max_meshes, params_format(*formats))
self.vertices = vertices
self.size = 0
2022-08-28 05:09:52 +02:00
self.max_size = max_size
self.flags = buffer(c_ubyte, max_size)
self.meshes = buffer(c_uint, max_size)
self.params = tuple(map(lambda f: buffer(param_type(f), max_size), formats))
self._params = (c_void_p * nparams)(*map(addressof, self.params))
for name, value in zip(names, self.params):
setattr(self, name, value)
2022-08-28 05:09:52 +02:00
def __del__(self):
destroy_batch(self._batch)
2022-12-31 21:02:46 +01:00
def spawn(self, model, *params):
assert len(params) == len(self.params)
index = self.size
2022-08-28 05:09:52 +02:00
assert index < self.max_size
2022-12-31 21:02:46 +01:00
self.flags[index] = model.flags | INSTANCE_FLAG_SPAWNED
self.meshes[index] = model.mesh
for self_params, param in zip(self.params, params):
self_params[index] = param
self.size += 1
return index
2022-08-28 05:09:52 +02:00
def draw(self):
draw_batch(self._batch, self.size, self.flags, self.meshes, self._params)