Skip to content

Commit 17a830f

Browse files
committed
object: add ability to tag arbitrary objects with arbitrary tags and values
Modules define lists of objects, e.g. a `SpriteRenderer` module may define ```zig sprites: mach.Objects(struct { // ... }), ``` Previously, the only way for another Mach module to 'attach data to a sprite object' or 'tag a sprite' would be to (ab)use the graph relations system, creating their own object and using parent/child relations to express that the sprite has some tag/data associated with it. For example: ```zig // Game.zig is_monster: mach.Object(struct{}), // empty object just to indicate 'some other object is a monster' // ... // Create a 'tag object' const is_monster_tag_obj_id = game.is_monster.new(.{}); // Add the 'tag object' as a child of our sprite sprite_renderer.sprites.addChild(my_sprite_id, is_monster_tag_obj_id); // ... ``` This usage of the API was quite ugly/usage, and importantly eliminated your ability to use the parent/child relations for _other_ things where they are more appropriate. However, it did mean that you didn't have to go and fork+modify the `SpriteRenderer` module that you e.g. imported as a reusable package. With this change, we add object _tags_ and _tags with values_. Any module can add their own tags or tags with values to any object, whether it is from their module or not. For example, the `is_monster` example above could now be written as: ```zig // Game.zig pub const mach_tags = .{ .is_monster }; // ... try sprite_renderer.sprites.setTag(sprite_id, Game, .is_monster, null); const is_monster: bool = sprite_renderer.sprites.hasTag(sprite_id, Game, .is_monster); // is_monster == true! // No longer a monster try sprite_renderer.sprites.removeTag(sprite_id, Game, .is_monster); ``` This allows for effectively tagging objects as distinct kinds, states, etc. even though they aren't our object and we can't modify their `struct {}` type to include an `is_monster: bool` field of our own. Internally, the implementation stores tags using a hashmap under the assumption that not all objects in a list will have a tag. Tags with values work almost identically, the only difference is that the last parameter to `setTag` is set to another `mach.ObjectID` which points to whatever arbitrary data you'd like to attach to the object, and `getTag` returns it. For example: ```zig // Game.zig pub const mach_tags = .{ /// Whether a sprite is a monster .is_monster, /// Whether a sprite has a friendly sprite attached to it .{ .friend, Sprite, .sprites }, }; // ... try sprite_renderer.sprites.setTag(sprite_id, Game, .friend, friendly_sprite_id); const has_friend: bool = sprite_renderer.sprites.hasTag(sprite_id, Game, .friend); // has_friend == true! // Get our friend const friend_id: mach.ObjectID = sprite_renderer.sprites.getTag(sprite_id, Game, .friend); // friend_id == friendly_sprite_id // Delete our friend try sprite_renderer.sprites.removeTag(sprite_id, Game, .friend); ``` Signed-off-by: Emi Gutekanst <[email protected]>
1 parent 9749cd9 commit 17a830f

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

src/module.zig

+94
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,21 @@ pub fn Objects(options: ObjectsOptions, comptime T: type) type {
7070

7171
/// A bitset used to track per-field changes. Only used if options.track_fields == true.
7272
updated: ?std.bit_set.DynamicBitSetUnmanaged = if (options.track_fields) .{} else null,
73+
74+
/// Tags storage
75+
tags: std.AutoHashMapUnmanaged(TaggedObject, ?ObjectID) = .{},
7376
},
7477

7578
pub const IsMachObjects = void;
7679

7780
const Generation = u16;
7881
const Index = u32;
7982

83+
const TaggedObject = struct {
84+
object_id: ObjectID,
85+
tag_hash: u64,
86+
};
87+
8088
const PackedID = packed struct(u64) {
8189
type_id: ObjectTypeID,
8290
generation: Generation,
@@ -275,6 +283,52 @@ pub fn Objects(options: ObjectsOptions, comptime T: type) type {
275283
if (mach.is_debug) data.set(unpacked.index, undefined);
276284
}
277285

286+
// TODO(objects): evaluate whether tag operations should ever return an error
287+
288+
/// Sets a tag on an object
289+
pub fn setTag(objs: *@This(), id: ObjectID, comptime M: type, tag: ModuleTagEnum(M), value_id: ?ObjectID) !void {
290+
_ = objs.validateAndUnpack(id, "setTag");
291+
292+
// TODO: validate that value_id is an object coming from the mach.Objects(T) list indicated by the tag value in M.mach_tags.
293+
//const value_mach_objects = moduleTagValueObjects(M, tag);
294+
295+
const tagged = TaggedObject{
296+
.object_id = id,
297+
.tag_hash = std.hash.Wyhash.hash(0, @tagName(tag)),
298+
};
299+
try objs.internal.tags.put(objs.internal.allocator, tagged, value_id);
300+
}
301+
302+
/// Removes a tag on an object
303+
pub fn removeTag(objs: *@This(), id: ObjectID, comptime M: type, tag: ModuleTagEnum(M)) void {
304+
_ = objs.validateAndUnpack(id, "setTag");
305+
const tagged = TaggedObject{
306+
.object_id = id,
307+
.tag_hash = std.hash.Wyhash.hash(0, @tagName(tag)),
308+
};
309+
_ = objs.internal.tags.remove(tagged);
310+
}
311+
312+
/// Whether an object has a tag
313+
pub fn hasTag(objs: *@This(), id: ObjectID, comptime M: type, tag: ModuleTagEnum(M)) bool {
314+
_ = objs.validateAndUnpack(id, "hasTag");
315+
const tagged = TaggedObject{
316+
.object_id = id,
317+
.tag_hash = std.hash.Wyhash.hash(0, @tagName(tag)),
318+
};
319+
return objs.internal.tags.contains(tagged);
320+
}
321+
322+
/// Get an object's tag value, or null.
323+
pub fn getTag(objs: *@This(), id: ObjectID, comptime M: type, tag: ModuleTagEnum(M)) ?mach.ObjectID {
324+
_ = objs.validateAndUnpack(id, "hasTag");
325+
const tagged = TaggedObject{
326+
.object_id = id,
327+
.tag_hash = std.hash.Wyhash.hash(0, @tagName(tag)),
328+
};
329+
return objs.internal.tags.get(tagged) orelse null;
330+
}
331+
278332
pub fn slice(objs: *@This()) Slice {
279333
return Slice{
280334
.index = 0,
@@ -497,6 +551,46 @@ fn ModuleFunctionName2(comptime M: type) type {
497551
});
498552
}
499553

554+
/// Enum describing all mach_tags for a given comptime-known module.
555+
fn ModuleTagEnum(comptime M: type) type {
556+
// TODO(object): handle duplicate enum field case in mach_tags with a more clear error?
557+
// TODO(object): improve validation error messages here
558+
validate(M);
559+
if (@typeInfo(@TypeOf(M.mach_tags)) != .@"struct") {
560+
@compileError("mach: invalid module, `pub const mach_tags must be `.{ .is_monster, .{ .renderer, mach.Renderer.objects } }`, found: " ++ @typeName(@TypeOf(M.mach_tags)));
561+
}
562+
var enum_fields: []const std.builtin.Type.EnumField = &[0]std.builtin.Type.EnumField{};
563+
var i: u32 = 0;
564+
inline for (@typeInfo(@TypeOf(M.mach_tags)).@"struct".fields, 0..) |field, field_index| {
565+
const f = M.mach_tags[field_index];
566+
if (@typeInfo(field.type) == .enum_literal) {
567+
enum_fields = enum_fields ++ [_]std.builtin.Type.EnumField{.{ .name = @tagName(f), .value = i }};
568+
i += 1;
569+
} else {
570+
if (@typeInfo(field.type) != .@"struct") {
571+
@compileError("mach: invalid module, mach_tags entry is not an enum literal or struct, found: " ++ @typeName(field.type));
572+
}
573+
// TODO(objects): validate length of struct
574+
const tag = f.@"0";
575+
const M2 = f.@"1";
576+
const object_list_tag = f.@"2";
577+
_ = object_list_tag; // autofix
578+
validate(M2);
579+
// TODO: validate that M2.object_list_tag is a mach objects list
580+
enum_fields = enum_fields ++ [_]std.builtin.Type.EnumField{.{ .name = @tagName(tag), .value = i }};
581+
i += 1;
582+
}
583+
}
584+
return @Type(.{
585+
.@"enum" = .{
586+
.tag_type = if (enum_fields.len > 0) std.math.IntFittingRange(0, enum_fields.len - 1) else u0,
587+
.fields = enum_fields,
588+
.decls = &[_]std.builtin.Type.Declaration{},
589+
.is_exhaustive = true,
590+
},
591+
});
592+
}
593+
500594
pub fn Modules(module_lists: anytype) type {
501595
inline for (moduleTuple(module_lists)) |module| {
502596
validate(module);

0 commit comments

Comments
 (0)