-
-
Notifications
You must be signed in to change notification settings - Fork 640
/
struct_array.ts
246 lines (214 loc) · 6.93 KB
/
struct_array.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Note: all "sizes" are measured in bytes
/**
* @internal
* A view type size
*/
const viewTypes = {
'Int8': Int8Array,
'Uint8': Uint8Array,
'Int16': Int16Array,
'Uint16': Uint16Array,
'Int32': Int32Array,
'Uint32': Uint32Array,
'Float32': Float32Array
};
/**
* @internal
* A view type size
*/
export type ViewType = keyof typeof viewTypes;
/** @internal */
class Struct {
_pos1: number;
_pos2: number;
_pos4: number;
_pos8: number;
readonly _structArray: StructArray;
// The following properties are defined on the prototype of sub classes.
size: number;
/**
* @param structArray - The StructArray the struct is stored in
* @param index - The index of the struct in the StructArray.
*/
constructor(structArray: StructArray, index: number) {
(this as any)._structArray = structArray;
this._pos1 = index * this.size;
this._pos2 = this._pos1 / 2;
this._pos4 = this._pos1 / 4;
this._pos8 = this._pos1 / 8;
}
}
const DEFAULT_CAPACITY = 128;
const RESIZE_MULTIPLIER = 5;
/**
* @internal
* A struct array memeber
*/
export type StructArrayMember = {
name: string;
type: ViewType;
components: number;
offset: number;
};
export type StructArrayLayout = {
members: Array<StructArrayMember>;
size: number;
alignment: number;
};
/**
* An array that can be desialized
*/
export type SerializedStructArray = {
length: number;
arrayBuffer: ArrayBuffer;
};
/**
* @internal
* `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`
* making it behave like an array of typed structs.
*
* Conceptually, a StructArray is comprised of elements, i.e., instances of its
* associated struct type. Each particular struct type, together with an
* alignment size, determines the memory layout of a StructArray whose elements
* are of that type. Thus, for each such layout that we need, we have
* a corresponding StructArrayLayout class, inheriting from StructArray and
* implementing `emplaceBack()` and `_refreshViews()`.
*
* In some cases, where we need to access particular elements of a StructArray,
* we implement a more specific subclass that inherits from one of the
* StructArrayLayouts and adds a `get(i): T` accessor that returns a structured
* object whose properties are proxies into the underlying memory space for the
* i-th element. This affords the convience of working with (seemingly) plain
* Javascript objects without the overhead of serializing/deserializing them
* into ArrayBuffers for efficient web worker transfer.
*/
abstract class StructArray {
capacity: number;
length: number;
isTransferred: boolean;
arrayBuffer: ArrayBuffer;
uint8: Uint8Array;
// The following properties are defined on the prototype.
members: Array<StructArrayMember>;
bytesPerElement: number;
abstract emplaceBack(...v: number[]);
abstract emplace(i: number, ...v: number[]);
constructor() {
this.isTransferred = false;
this.capacity = -1;
this.resize(0);
}
/**
* Serialize a StructArray instance. Serializes both the raw data and the
* metadata needed to reconstruct the StructArray base class during
* deserialization.
*/
static serialize(array: StructArray, transferables?: Array<Transferable>): SerializedStructArray {
array._trim();
if (transferables) {
array.isTransferred = true;
transferables.push(array.arrayBuffer);
}
return {
length: array.length,
arrayBuffer: array.arrayBuffer,
};
}
static deserialize(input: SerializedStructArray) {
const structArray = Object.create(this.prototype);
structArray.arrayBuffer = input.arrayBuffer;
structArray.length = input.length;
structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;
structArray._refreshViews();
return structArray;
}
/**
* Resize the array to discard unused capacity.
*/
_trim() {
if (this.length !== this.capacity) {
this.capacity = this.length;
this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);
this._refreshViews();
}
}
/**
* Resets the length of the array to 0 without de-allocating capcacity.
*/
clear() {
this.length = 0;
}
/**
* Resize the array.
* If `n` is greater than the current length then additional elements with undefined values are added.
* If `n` is less than the current length then the array will be reduced to the first `n` elements.
* @param n - The new size of the array.
*/
resize(n: number) {
this.reserve(n);
this.length = n;
}
/**
* Indicate a planned increase in size, so that any necessary allocation may
* be done once, ahead of time.
* @param n - The expected size of the array.
*/
reserve(n: number) {
if (n > this.capacity) {
this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);
this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);
const oldUint8Array = this.uint8;
this._refreshViews();
if (oldUint8Array) this.uint8.set(oldUint8Array);
}
}
/**
* Create TypedArray views for the current ArrayBuffer.
*/
_refreshViews() {
throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');
}
}
/**
* Given a list of member fields, create a full StructArrayLayout, in
* particular calculating the correct byte offset for each field. This data
* is used at build time to generate StructArrayLayout_*#emplaceBack() and
* other accessors, and at runtime for binding vertex buffer attributes.
*/
function createLayout(
members: Array<{
name: string;
type: ViewType;
readonly components?: number;
}>,
alignment: number = 1
): StructArrayLayout {
let offset = 0;
let maxSize = 0;
const layoutMembers = members.map((member) => {
const typeSize = sizeOf(member.type);
const memberOffset = offset = align(offset, Math.max(alignment, typeSize));
const components = member.components || 1;
maxSize = Math.max(maxSize, typeSize);
offset += typeSize * components;
return {
name: member.name,
type: member.type,
components,
offset: memberOffset,
};
});
const size = align(offset, Math.max(maxSize, alignment));
return {
members: layoutMembers,
size,
alignment
};
}
function sizeOf(type: ViewType): number {
return viewTypes[type].BYTES_PER_ELEMENT;
}
function align(offset: number, size: number): number {
return Math.ceil(offset / size) * size;
}
export {StructArray, Struct, viewTypes, createLayout};