+(define (make-entity-set . changes)
+ (modify-entities (bongodb:make-collection) changes))
+
+(define (entity-list entity-set)
+ (bongodb:find entity-set))
+
+(define (entity-count entity-set)
+ (bongodb:count entity-set))
+
+(define (normalize-components components)
+ (map
+ (lambda (c)
+ (if (record? c)
+ `(,(get-component-type c) . ,c)
+ c))
+ components))
+
+(define (entity-ref key entity-set)
+ (hash-get-handle (car entity-set) key))
+
+(define (new-entity entity-set . new-components)
+ (receive (new-set new-keys) (bongodb:insert entity-set (normalize-components new-components))
+ (values new-set (car new-keys))))
+
+(define (get-entity entity-set key)
+ (let ((entity (bongodb:find entity-set (bongodb:$eq '_id key))))
+ (and entity (car entity))))
+
+(define (remove-entity key)
+ (lambda (entity-set)
+ (let ((clist (entity-component-names key entity-set))
+ (entity (entity-ref key entity-set)))
+ (hash-remove! (car entity-set) key)
+ (unregister-components key clist (cdr entity-set))
+ (values
+ entity-set
+ entity))))
+
+(define (set-entity key . new-components)
+ (lambda (entity-set)
+ (let* ((nc (normalize-components new-components))
+ (clist (entity-component-names key entity-set))
+ (nclist (component-names nc)))
+ (hash-set! (car entity-set) key nc)
+ (register-components key
+ (lset-difference eq? nclist clist)
+ (unregister-components key (lset-difference eq? clist nclist) (cdr entity-set)))
+ (values
+ entity-set
+ (cons key nc)))))
+
+(define (set-entity-components key . new-components)
+ (lambda (entity-set)
+ (let ((nc (normalize-components new-components))
+ (clist (alist-copy (hash-ref (car entity-set) key))))
+ (for-each
+ (lambda (c)
+ (set! clist (assoc-set! clist (car c) (cdr c))))
+ nc)
+ (hash-set! (car entity-set) key clist)
+ (register-components key (component-names nc) (cdr entity-set))
+ (values
+ entity-set
+ (cons key clist)))))
+
+(define (remove-entity-components key . old-components)
+ (lambda (entity-set)
+ (let ((clist (alist-copy (hash-ref (car entity-set) key))))
+ (for-each
+ (lambda (c)
+ (set! clist (assoc-remove! clist c)))
+ old-components)
+ (hash-set! (car entity-set) key clist)
+ (unregister-components key old-components (cdr entity-set))
+ (values
+ entity-set
+ (cons key clist)))))
+
+(define (modify-entities entity-set changes)
+ (cond ((null? changes)
+ entity-set)