/*
 *                            COPYRIGHT
 *
 *  camv-rnd - electronics-related CAM viewer
 *  Copyright (C) 2019 Tibor 'Igor2' Palinkas
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 31 Milk Street, # 960789 Boston, MA 02196 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/camv-rnd
 *    lead developer: http://repo.hu/projects/camv-rnd/contact.html
 *    mailing list: pcb-rnd (at) list.repo.hu (send "subscribe")
 */

#ifndef CAMV_OBJ_ANY_H
#define CAMV_OBJ_ANY_H

#include <assert.h>

#include "camv_typedefs.h"
#include "data.h"
#include "obj_common.h"
#include "obj_arc.h"
#include "obj_line.h"
#include "obj_poly.h"
#include "obj_grp.h"
#include "obj_text.h"

typedef struct camv_proto_s {
	CAMV_ANY_PRIMITIVE_FIELDS;
} camv_proto_t;

union camv_any_obj_u {
	camv_proto_t proto;
	camv_arc_t arc;
	camv_line_t line;
	camv_poly_t poly;
	camv_grp_t grp;
	camv_text_t text;
};

void camv_obj_add_to_layer(camv_layer_t *ly, camv_any_obj_t *obj);

/* Allocate a new object and copy all fields from src, except for parent data */
camv_any_obj_t *camv_obj_dup(const camv_any_obj_t *src);

RND_INLINE camv_layer_t *camv_obj_parent_layer(const camv_any_obj_t *obj);
RND_INLINE camv_design_t *camv_obj_parent_design(const camv_any_obj_t *obj);
RND_INLINE camv_rtree_box_t *camv_obj_bbox(camv_any_obj_t *obj);

/*** implementation (inlines) ***/

RND_INLINE camv_layer_t *camv_obj_parent_layer(const camv_any_obj_t *obj)
{
	while(obj->proto.parent_obj != NULL) obj = obj->proto.parent_obj;
	return obj->proto.parent_layer;
}

RND_INLINE camv_design_t *camv_obj_parent_design(const camv_any_obj_t *obj)
{
	camv_layer_t *ly = camv_obj_parent_layer(obj);
	if (ly == NULL)
		return NULL;
	return ly->parent;
}

RND_INLINE camv_rtree_box_t *camv_obj_bbox(camv_any_obj_t *obj)
{
	if (!obj->proto.bbox_valid)
		obj->proto.calls->bbox(obj);
	assert(obj->proto.bbox_valid);
	return &obj->proto.bbox;
}

RND_INLINE void camv_obj_free(camv_any_obj_t *obj)
{
	obj->proto.calls->free_fields(obj);
	free(obj);
}

#endif
