+
+
+// motor stuff
+
+static void update_motor_vars(ParserState *ps, Motor *motor)
+{
+ std::map<std::string, Value>::const_iterator it = ps->var.begin();
+ while(it != ps->var.end()) {
+ set_motor_var(ps, motor, it->first.c_str(), it->second);
+ ++it;
+ }
+}
+
+static bool set_motor_var(ParserState *ps, Motor *motor, const char *name, const Value &val)
+{
+ if(strcmp(name, "drive") == 0) {
+ ASSERT_TYPE(val, VAL_STR);
+ Gear *gear = ps->gears[val.s];
+ if(!gear) {
+ errmsg(ps, "undefined gear: %s", val.s.c_str());
+ return false;
+ }
+ int idx = ps->mcn->get_gear_index(gear);
+ assert(idx >= 0);
+ motor->drive = idx;
+
+ } else if(strcmp(name, "speed") == 0) {
+ ASSERT_TYPE(val, VAL_NUM);
+ motor->speed = val.v[0];
+
+ } else {
+ return false;
+ }
+ return true;
+}
+
+
+// built-in functions
+static bool func_adjacent(ParserState *ps)
+{
+ Value val_angle = ps->val.top(); ps->val.pop();
+ Value val_gear_name = ps->val.top(); ps->val.pop();
+
+ if(val_gear_name.type != VAL_STR) {
+ expected(ps, "gear name (string) as 1st arg to adjacent");
+ return false;
+ }
+ if(val_angle.type != VAL_NUM) {
+ expected(ps, "angle as 2nd arg to adjacent");
+ return false;
+ }
+
+ Gear *gthis = this_gear(ps);
+ if(!gthis) {
+ errmsg(ps, "adjacent: called outside of a gear block");
+ return false;
+ }
+
+ Gear *gother = ps->gears[val_gear_name.s];
+ if(!gother) {
+ errmsg(ps, "adjacent: gear \"%s\" not found", val_gear_name.s.c_str());
+ return false;
+ }
+
+ Mat4 xform;
+ xform.rotation(deg_to_rad(val_angle.v[0]), gother->axis);
+ Vec3 dir = xform * Vec3(0, 1, 0);
+
+ float sum_radii = gthis->radius + gother->radius;
+ float avg_teeth_len = (gthis->teeth_length + gother->teeth_length) * 0.5;
+ Vec3 pos = gother->pos + dir * (sum_radii - avg_teeth_len * 0.75);
+
+ Value res;
+ res.type = VAL_VEC;
+ res.v[0] = pos.x;
+ res.v[1] = pos.y;
+ res.v[2] = pos.z;
+ ps->val.push(res);
+ return true;
+}
+
+static bool func_coaxial(ParserState *ps)
+{
+ Value val_dist = ps->val.top(); ps->val.pop();
+ Value val_gear_name = ps->val.top(); ps->val.pop();
+
+ if(val_gear_name.type != VAL_STR) {
+ expected(ps, "gear name (string) as 1st arg to func_coaxial");
+ return false;
+ }
+ if(val_dist.type != VAL_NUM) {
+ expected(ps, "stacking distance as 2nd arg to func_coaxial");
+ return false;
+ }
+
+ Gear *gthis = this_gear(ps);
+ if(!gthis) {
+ errmsg(ps, "coaxial: called outside of a gear block");
+ return false;
+ }
+
+ Gear *gother = find_gear(ps, val_gear_name.s.c_str());
+ if(!gother) {
+ errmsg(ps, "coaxial: gear \"%s\" not found", val_gear_name.s.c_str());
+ return false;
+ }
+
+ float avg_thickness = (gthis->thickness + gother->thickness) * 0.5;
+ Vec3 pos = gother->pos + gother->axis * val_dist.v[0] * avg_thickness;
+
+ Value res;
+ res.type = VAL_VEC;
+ res.v[0] = pos.x;
+ res.v[1] = pos.y;
+ res.v[2] = pos.z;
+ ps->val.push(res);
+ return true;
+}