Пример #1
0
void rbarray(double *a) {
	for (int i = 0; i < sz; i++) {
		if (RB(i) < i) {
			double t1 = a[i*2], t2 = a[i*2+1];
			a[i*2] = a[RB(i)*2];
			a[i*2+1] = a[RB(i)*2+1];
			a[RB(i)*2] = t1;
			a[RB(i)*2+1] = t2;
		}
	}
}
Пример #2
0
SSIZE_T parse( BYTE *data, SIZE_T len, Descriptors &descriptors ) {
	SSIZE_T offset = 0;

	WORD compatibilityLen = RW(data,offset);
	if (!compatibilityLen) {
		//	Ignore if not present
		return 2;
	}
	WORD descriptorCount  = RW(data,offset);

	printf( "[dsmcc::compatiblity] Compatibility descriptor: dataLen=%ld, descLen=%d, count=%d\n",
	 	len, compatibilityLen, descriptorCount );

	//	Check if len is ok
	if (len < compatibilityLen) {
		printf( "[dsmcc::compatiblity] No data available to parse Compatibility descriptor: descLen=%ld, available=%d\n",
			len, compatibilityLen );
		return compatibilityLen+2;
	}

	//	Parse descriptors
	for (WORD desc=0; desc<descriptorCount; desc++) {
		Descriptor desc;

		desc.type      = RB(data,offset);
		
		//BYTE dLen      = RB(data,offset);
		offset += 1;
		
		desc.specifier = RDW(data,offset);
		desc.model     = RW(data,offset);
		desc.version   = RW(data,offset);

		//	Parse sub descriptors
		BYTE subCount = RB(data,offset);		
		for (BYTE sub=0; sub<subCount; sub++) {
			BYTE subType = RB(data,offset);
			BYTE subLen  = RB(data,offset);
			//	AdditionalInformation
			offset += subLen;
			printf( "[dsmcc::compatibility] Warning, subdescriptor not parsed: count=%d, type=%x, len=%x\n", subCount, subType, subLen );
		}

		descriptors.push_back( desc );
	}
	
	return compatibilityLen+2; 
}
Пример #3
0
/*******************************************************************************
 *
 * Render backend context functions.
 *
 ******************************************************************************/
int
rb_create_context
  (struct mem_allocator* specific_allocator,
   struct rb_context** out_ctxt)
{
  struct mem_allocator* allocator = NULL;
  struct rb_context* ctxt = NULL;
  int err = 0;

  if(!out_ctxt)
    goto error;

  allocator = specific_allocator ? specific_allocator : &mem_default_allocator;
  ctxt = MEM_CALLOC(allocator, 1, sizeof(struct rb_context));
  if(!ctxt)
    goto error;
  ctxt->allocator = allocator;
  ref_init(&ctxt->ref);

  setup_config(&ctxt->config);

exit:
  if(ctxt)
    *out_ctxt = ctxt;
  return err;

error:
  if(ctxt) {
    RB(context_ref_put(ctxt));
    ctxt = NULL;
  }
  err = -1;
  goto exit;
}
Пример #4
0
static void
release_vertex_array(struct ref* ref)
{
  struct rb_context* ctxt = NULL;
  struct rb_vertex_array* varray = NULL;
  assert(ref);

  varray = CONTAINER_OF(ref, struct rb_vertex_array, ref);
  ctxt = varray->ctxt;

  if(ctxt->state_cache.vertex_array_binding == varray->name)
    RB(bind_vertex_array(ctxt, NULL));

  OGL(DeleteVertexArrays(1, &varray->name));
  MEM_FREE(ctxt->allocator, varray);
  RB(context_ref_put(ctxt));
}
Пример #5
0
static void
release_uniform(struct ref* ref)
{
  struct rb_context* ctxt = NULL;
  struct rb_uniform* uniform = NULL;
  assert(ref);

  uniform = CONTAINER_OF(ref, struct rb_uniform, ref);
  ctxt = uniform->ctxt;

  if(uniform->program)
    RB(program_ref_put(uniform->program));
  if(uniform->name)
    MEM_FREE(ctxt->allocator, uniform->name);
  MEM_FREE(ctxt->allocator, uniform);
  RB(context_ref_put(ctxt));
}
Пример #6
0
void PocketPCLandscapeAspect(const uint8 *srcPtr, uint32 srcPitch, uint8 *dstPtr, uint32 dstPitch, int width, int height) {

#define RB(x) ((x & redblueMasks[maskUsed])<<8)
#define G(x)  ((x & greenMasks[maskUsed])<<3)

#define P20(x) (((x)>>2)-((x)>>4))
#define P40(x) (((x)>>1)-((x)>>3))
#define P60(x) (((x)>>1)+((x)>>3))
#define P80(x) (((x)>>1)+((x)>>2)+((x)>>4))

#define MAKEPIXEL(rb,g) ((((rb)>>8) & redblueMasks[maskUsed] | ((g)>>3) & greenMasks[maskUsed]))

	int i,j;
	unsigned int p1;
	unsigned int p2;
	uint16 * inbuf;
	uint16 * outbuf;
	inbuf=(uint16 *)srcPtr;
	outbuf=(uint16 *)dstPtr;

	uint16 srcPitch16 = (uint16)(srcPitch / sizeof(uint16));
	uint16 dstPitch16 = (uint16)(dstPitch / sizeof(uint16));

	for (i=0; i<((height)/6); i++) {
        for (j=0; j<width; j++) {
			p1=*((uint16*)inbuf+j);
			inbuf+=srcPitch16;
			*((uint16*)outbuf+j)=p1;
			outbuf+=dstPitch16;
			p2=*((uint16*)inbuf+j);
			inbuf+=srcPitch16;
			*((uint16*)outbuf+j)=MAKEPIXEL(P20(RB(p1))+P80(RB(p2)),P20(G(p1))+P80(G(p2)));  
			outbuf+=dstPitch16;
			p1=p2; 
			p2=*((uint16*)inbuf+j);
			inbuf+=srcPitch16;
			*((uint16*)outbuf+j)=MAKEPIXEL(P40(RB(p1))+P60(RB(p2)),P40(G(p1))+P60(G(p2)));  
			outbuf+=dstPitch16;
			p1=p2;
			p2=*((uint16*)inbuf+j);
			inbuf+=srcPitch16;
			*((uint16*)outbuf+j)=MAKEPIXEL(P60(RB(p1))+P40(RB(p2)),P60(G(p1))+P40(G(p2)));  
			outbuf+=dstPitch16;
			p1=p2;
			p2=*((uint16*)inbuf+j);
			*((uint16*)outbuf+j)=MAKEPIXEL(P80(RB(p1))+P20(RB(p2)),P80(G(p1))+P20(G(p2)));  
			outbuf+=dstPitch16;
			*((uint16*)outbuf+j)=p2;
			inbuf=inbuf-srcPitch16*4;   
			outbuf=outbuf-dstPitch16*5; 
		}      
        inbuf=inbuf+srcPitch16*5;
        outbuf=outbuf+dstPitch16*6;
	}
}
Пример #7
0
bool b2WheelJoint::SolvePositionConstraints(float32 baumgarte)
{
	B2_NOT_USED(baumgarte);

	b2Body* bA = m_bodyA;
	b2Body* bB = m_bodyB;

	b2Vec2 xA = bA->m_sweep.c;
	float32 angleA = bA->m_sweep.a;

	b2Vec2 xB = bB->m_sweep.c;
	float32 angleB = bB->m_sweep.a;

	b2Mat22 RA(angleA), RB(angleB);

	b2Vec2 rA = b2Mul(RA, m_localAnchorA - m_localCenterA);
	b2Vec2 rB = b2Mul(RB, m_localAnchorB - m_localCenterB);
	b2Vec2 d = xB + rB - xA - rA;

	b2Vec2 ay = b2Mul(RA, m_localYAxisA);

	float32 sAy = b2Cross(d + rA, ay);
	float32 sBy = b2Cross(rB, ay);

	float32 C = b2Dot(d, ay);

	float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;

	float32 impulse;
	if (k != 0.0f)
	{
		impulse = - C / k;
	}
	else
	{
		impulse = 0.0f;
	}

	b2Vec2 P = impulse * ay;
	float32 LA = impulse * sAy;
	float32 LB = impulse * sBy;

	xA -= m_invMassA * P;
	angleA -= m_invIA * LA;
	xB += m_invMassB * P;
	angleB += m_invIB * LB;

	// TODO_ERIN remove need for this.
	bA->m_sweep.c = xA;
	bA->m_sweep.a = angleA;
	bB->m_sweep.c = xB;
	bB->m_sweep.a = angleB;
	bA->SynchronizeTransform();
	bB->SynchronizeTransform();

	return b2Abs(C) <= b2_linearSlop;
}
Пример #8
0
void packet_print(){
	short x = (X_SIGN(packet[0]) ? (packet[1] | (0xff << 8)) : packet[1]);
	short y = (Y_SIGN(packet[0]) ? (packet[2] | (0xff << 8)) : packet[2]);
	printf("B1=0x%x B2=0x%x B3=0x%x LB=%d MB=%d RB=%d XOV=%d YOV=%d X=%d Y=%d \n",
			packet[0], packet[1], packet[2],
			LB(packet[0]), MB(packet[0]), RB(packet[0]),
			X_OVF(packet[0]), Y_OVF(packet[0]),
			x, y);
	counter = 0;
}
Пример #9
0
    vector<Point2F> Square::GetCorners() const {
        vector<Point2F> v;
        v.reserve(4);

        v.push_back(LT());
        v.push_back(LB());
        v.push_back(RT());
        v.push_back(RB());

        return v;
    }
	/* Extract quantization threshold from preamble sequence */
	int32_t extractThreshold(void)
	{
		int32_t threshold = 0;
		int c;
		for (c = 0; c < 16 /* 2 * srate */; c++) {
			//XXX: threshold += (int32_t)_ringbuffer.get(c);
			threshold += (int32_t)RB(c);
		}

		return (int32_t)threshold / 16; // 8 * g_srate
	}
Пример #11
0
SSIZE_T parse( BYTE *data, SIZE_T /*len*/, Modules &modules, bool skipVersion/*=false*/ ) {
	SSIZE_T offset = 0;
	
	WORD numberOfModules = RW(data,offset);
    for (int mod=0; mod<numberOfModules; mod++) {
		Type module;

        module.id      = RW(data,offset);
        module.size    = RDW(data,offset);
		module.version = (skipVersion) ? 0 : RB(data,offset);
        BYTE moduleInfoLen = RB(data,offset);
        if (moduleInfoLen) {
            module.info.copy( (char *)(data+offset), moduleInfoLen );
            offset += moduleInfoLen;
        }

		modules.push_back( module );
    }

	return offset;
}
Пример #12
0
int main()
{
	double *a = calloc(sz*2, sizeof(double));
	for (int i = 0; i < 4; i++) {
		scanf("%lf",&a[RB(i)*2]);
		a[RB(i)*2+1] = 0;
	}
	dft(a, false);
	for (int i = 0; i < sz; i++) {
		double rr = a[i*2], ii = a[i*2+1];
		a[i*2] = rr*rr-ii*ii;
		a[i*2+1] = rr*ii+rr*ii;
	}

	rbarray(a);
	dft(a, true);

	for (int i = 0; i < 7; i++) {
		printf("%.6f\n", a[i*2] / sz);
	}
	free(a);
	return 0;
}
	bool feedOne(const uint16_t sample)
	{
		//XXX: _ringbuffer.increment();
		//_ringbuffer.put((int)sample);
		RB_inc();
		RB(0) = (int)sample;

		if (--_skip < 1) {
			if (decodePacket(++_samples)) {
				_skip = 20;
				return true;
			}
		}
		return false;
	}
Пример #14
0
/*******************************************************************************
 *
 * Uniform implementation.
 *
 ******************************************************************************/
int
rb_get_named_uniform
  (struct rb_context* ctxt,
   struct rb_program* program,
   const char* name,
   struct rb_uniform** out_uniform)
{
  struct rb_uniform* uniform = NULL;
  GLuint uniform_index = GL_INVALID_INDEX;
  size_t name_len = 0;
  int err = 0;

  if(!ctxt || !program || !name || !out_uniform)
    goto error;

  if(!program->is_linked)
    goto error;

  OGL(GetUniformIndices(program->name, 1, &name, &uniform_index));
  if(uniform_index == GL_INVALID_INDEX)
    goto error;

  err = get_active_uniform(ctxt, program, uniform_index, 0, NULL, &uniform);
  if(err != 0)
    goto error;

  name_len = strlen(name) + 1;
  uniform->name = MEM_ALLOC(ctxt->allocator, sizeof(char) * name_len);
  if(!uniform->name)
    goto error;

  uniform->name = strncpy(uniform->name, name, name_len);
  uniform->location = OGL(GetUniformLocation(program->name, uniform->name));

exit:
  *out_uniform = uniform;
  return err;

error:
  if(uniform) {
    RB(uniform_ref_put(uniform));
    uniform = NULL;
  }
  err = -1;
  goto exit;
}
Пример #15
0
static void
release_buffer(struct ref* ref)
{
  struct rb_buffer* buffer = NULL;
  struct rb_context* ctxt = NULL;
  ASSERT(ref);

  buffer = CONTAINER_OF(ref, struct rb_buffer, ref);
  ctxt = buffer->ctxt;

  if(buffer->name == ctxt->state_cache.buffer_binding[buffer->binding])
    OGL(BindBuffer(buffer->target, 0));
 
  OGL(DeleteBuffers(1, &buffer->name));
  MEM_FREE(ctxt->allocator, buffer);
  RB(context_ref_put(ctxt));
}
Пример #16
0
void vm_mini_vm(lua_State *L, LClosure *cl, int count, int pseudo_ops_offset) {
  const Instruction *pc;
  StkId base;
  TValue *k;

  k = cl->p->k;
  pc = cl->p->code + pseudo_ops_offset;
  base = L->base;
  /* process next 'count' ops */
  for (; count > 0; count--) {
    const Instruction i = *pc++;
    StkId ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      default: {
        luaG_runerror(L, "Bad opcode: opcode=%d", GET_OPCODE(i));
        continue;
      }
    }
  }
}
Пример #17
0
SSIZE_T Object::objectKey( const BYTE *data, SIZE_T len, ObjectKeyType &key ) {
    SSIZE_T off=0;

    //  Object key len
    BYTE objectKeyLen = RB(data,off);
    if (objectKeyLen > 4) {
        throw std::bad_cast();
    }
    assert(len >= SIZE_T(1+objectKeyLen));
	
    //  Object key
	key = RDW( data, off );

	//printf( "[dsmcc::Object] Parsing object key: len=%08lx, key=%08lx\n", len, key );

    return off;
}
Пример #18
0
void luaV_execute (lua_State *L) {
  CallInfo *ci = L->ci;
  LClosure *cl;
  TValue *k;
  StkId base;
 newframe:  /* reentry point when frame changes (call/return) */
  lua_assert(ci == L->ci);
  cl = clLvalue(ci->func);
  k = cl->p->k;
  base = ci->u.l.base;

  //printf( "s:%p\n", ci->u.l.savedpc );
  /* main loop of interpreter */
  for (;;) {

    Instruction i = *(ci->u.l.savedpc++);
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      Protect(traceexec(L));
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == ci->u.l.base);
    lua_assert(base <= L->top && L->top < L->stack + L->stacksize);


    // 命令出力
    //printInst( ci->u.l.savedpc - 1 );


    vmdispatch (GET_OPCODE(i)) {
      vmcase(OP_MOVE,
        setobjs2s(L, ra, RB(i));
      )
      vmcase(OP_LOADK,
        TValue *rb = k + GETARG_Bx(i);
        setobj2s(L, ra, rb);
      )
      vmcase(OP_LOADKX,
        TValue *rb;
        lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
        rb = k + GETARG_Ax(*ci->u.l.savedpc++);
        setobj2s(L, ra, rb);
      )
Пример #19
0
int test_config(void) {
	unsigned long byte;
	subscribe_mouse();
	mouse_write_byte(DISABLE_DATA_PACKETS);
	mouse_write_byte(STATUS_REQUEST);
	byte = mouse_read();
	if(byte == -1) return 1;
	printf("byte 1: 0x%X\n", byte);
	printf("Scaling: ");
	if(!SCALING(byte))
		printf("1:1  ");
	else
		printf("2:1  ");
	printf("Data Reporting: ");
	if(!DATA_REPORTING(byte))
		printf("disable  ");
	else
		printf("enable   ");
	printf("Mode: ");
	if(!MODE(byte))
		printf("remote mode\n\n");
	else
		printf("stream mode\n\n");
	if(LB(byte))
		printf("LB: pressed ");
	else
		printf("LB: not pressed ");
	if(RB(byte))
		printf("RB: pressed ");
	else
		printf("RB: not pressed ");
	if(MB(byte))
		printf("MB: pressed ");
	else
		printf("MB: not pressed ");
	byte = mouse_read();
	if(byte == -1) return 1;
	printf("\n byte 2: 0x%X\n", byte);
	printf("Resolution: %d\n\n", byte);
	byte = mouse_read();
	if(byte == -1) return 1;
	printf("byte 3: 0x%X\n", byte);
	printf("Sample Rate: %d\n\n", byte);
}
Пример #20
0
/*******************************************************************************
 *
 * Vertex array functions.
 *
 ******************************************************************************/
int
rb_create_vertex_array
  (struct rb_context* ctxt,
   struct rb_vertex_array** out_array)
{
  struct rb_vertex_array* array = NULL;

  if(!ctxt || !out_array)
    return -1;

  array = MEM_ALLOC(ctxt->allocator, sizeof(struct rb_vertex_array));
  if(!array)
    return -1;
  ref_init(&array->ref);
  RB(context_ref_get(ctxt));
  array->ctxt = ctxt;

  OGL(GenVertexArrays(1, &array->name));
  *out_array = array;
  return 0;
}
Пример #21
0
/*******************************************************************************
 *
 * Private functions.
 *
 ******************************************************************************/
int
rb_ogl3_create_buffer
  (struct rb_context* ctxt,
   const struct rb_ogl3_buffer_desc* desc,
   const void* init_data,
   struct rb_buffer** out_buffer)
{
  struct rb_buffer* buffer = NULL;

  if(!ctxt
  || !desc
  || !out_buffer
  || (desc->target == RB_OGL3_NB_BUFFER_TARGETS)
  || (desc->usage == RB_USAGE_IMMUTABLE && init_data == NULL))
    return -1;

  buffer = MEM_ALLOC(ctxt->allocator, sizeof(struct rb_buffer));
  if(!buffer)
    return -1;
  ref_init(&buffer->ref);
  RB(context_ref_get(ctxt));
  buffer->ctxt = ctxt;

  buffer->target = rb_to_ogl3_buffer_target(desc->target);
  buffer->usage = rb_to_ogl3_usage(desc->usage);
  buffer->size = (GLsizei)desc->size;
  buffer->binding = desc->target;

  OGL(GenBuffers(1, &buffer->name));
  OGL(BindBuffer(buffer->target, buffer->name));
  OGL(BufferData(buffer->target, buffer->size, init_data, buffer->usage));
  OGL(BindBuffer
    (buffer->target, 
     ctxt->state_cache.buffer_binding[buffer->binding]));

  *out_buffer = buffer;
  return 0;
}
Пример #22
0
Object *Object::parseObject( ResourceManager *resMgr, Module *module, SSIZE_T &off ) {
    Object *obj;
	ObjectLocation loc;
    BYTE buf[BIOP_MAX_HEADER];

    SSIZE_T offset = 0;
    SIZE_T len = module->read( off, buf, BIOP_MAX_HEADER );
    if (len < BIOP_MAX_HEADER) {
        printf( "[dsmcc::Object] Warning: Not enough buffer: len=%ld, offset=%ld\n", len, offset );
        return NULL;
    }

    DWORD magic = RDW(buf,offset);
    if (magic != BIOP_MAGIC) {
        printf( "[dsmcc::Object] Warning: Bad magic number: magic=%x, found=%lx\n", BIOP_MAGIC, magic );
        return NULL;
    }

    WORD biopVersion = RW(buf,offset);
    if (biopVersion != BIOP_VER) {
        printf( "[dsmcc::Object] Warning: Invalid version\n" );
        return NULL;
    }

    BYTE byteOrder = RB(buf,offset);
    if (byteOrder) {
        printf( "[dsmcc::Object] Warning: Invalid byte order\n" );
        return NULL;
    }

    BYTE msgType = RB(buf,offset);
    if (msgType) {
        printf( "[dsmcc::Object] Warning: Invalid type\n" );
        return NULL;
    }

    //  Check BIOP message size
    DWORD msgSize = RDW(buf,offset);
    if (module->size()-off-offset < msgSize) {
        printf( "[dsmcc::Object] Warning: Not enough bytes for BIOP message: msgSize=%ld, rest%ld\n", msgSize, module->size()-off-offset );
        return NULL;
    }
    //  12 bytes parsed = BIOP_MIN_HEADER

    offset += objectKey( buf+offset, len-offset, loc.keyID );

    DWORD objectKindLen = RDW(buf,offset);
    if (objectKindLen != 4) {
        printf( "[dsmcc::Object] Warning: Invalid object kind\n" );
        return NULL;
    }

	//	Chapter 11: The downloadID field of the DownloadDataBlock messages shall have the same value
	//	as the carouselID field of the U-U Object Carousel
	loc.carouselID = module->downloadID();
	loc.moduleID   = module->id();

    DWORD objectKind = RDW(buf,offset);
    switch (objectKind) {
        case BIOP_OBJECT_FILE:
            obj = new File( loc );
            break;
        case BIOP_OBJECT_DIR:
        case BIOP_OBJECT_GW:
            obj = new Directory( loc );
            break;
		// case BIOP_OBJECT_STR:
		// 	break;
		case BIOP_OBJECT_STE:
			obj = new StreamEvent( loc );
			break;
        default:
            obj = NULL;
            printf( "[dsmcc::Object] Warning: BIOP object kind %lx not processed\n", objectKind );
    }

	WORD objectInfoLen = RW(buf,offset);
	
    //  Update offset (27 bytes parsed = BIOP_MAX_HEADER)
    off += offset;
    if (obj && !obj->parse( resMgr, module, off, objectInfoLen )) {
		delete obj;
		obj = NULL;
	}
	
    return obj;
}
Пример #23
0
//--------------------------------------------------------------
void testApp::setup(){
	cout << "ITU: " << Ritu_db(1000) << "dB => " << Ritu(6000) << endl;
	cout << "A: " << RA_db(1000) << "dB => " << RA(1000) << endl;
	cout << "B: " << RB_db(1000) << "dB => " << RB(1000) << endl;
	cout << "C: " << RC_db(1000) << "dB => " << RC(1000) << endl;
	cout << "D: " << RD_db(1000) << "dB => " << RD(1000) << endl;
	
	/* some standard setup stuff*/
	ofEnableAlphaBlending();
	ofSetupScreen();
	ofBackground(0, 0, 0);
	ofSetFrameRate(20);
	ofSetVerticalSync(false);

	EscalaF = 1.015;
	
	/* This is stuff you always need.*/
	sampleRate 			= 44100; /* Sampling Rate */
	initialBufferSize	= 512;	/* Buffer Size. you have to fill this buffer with sound*/
	lAudioOut			= new float[initialBufferSize];/* outputs */
	rAudioOut			= new float[initialBufferSize];
	lAudioIn			= new float[initialBufferSize];/* inputs */
	rAudioIn			= new float[initialBufferSize];
	
	/* This is a nice safe piece of code */
	memset(lAudioOut, 0, initialBufferSize * sizeof(float));
	memset(rAudioOut, 0, initialBufferSize * sizeof(float));
	
	memset(lAudioIn, 0, initialBufferSize * sizeof(float));
	memset(rAudioIn, 0, initialBufferSize * sizeof(float));
	
	//	samp.load(ofToDataPath("sinetest_stepping2.wav"));
	//	samp.load(ofToDataPath("whitenoise2.wav"));
	//	samp.load(ofToDataPath("additive22.wav"));
	//  samp.load(ofToDataPath("pinknoise2.wav"));
	//  samp.setLength(sampleRate*8);
	//  samp.clear();
	  samp.load(ofToDataPath("sweep_0_22K.wav"));
		
	fftSize = 1024;
	mfft.setup(fftSize, 512, 256);
	ifft.setup(fftSize, 512, 256);
		
	nAverages = 12;
	oct.setup(sampleRate, fftSize/2, nAverages);
	
	mfccs = (double*) malloc(sizeof(double) * 13);
	mfcc.setup(512, 42, 13, 1, 22050, sampleRate);
	
	ofxMaxiSettings::setup(sampleRate, 2, initialBufferSize);
	soundStream.setDeviceID(0);
	soundStream.listDevices();
	//ofSoundStreamSetup(2,2, this, sampleRate, initialBufferSize, 4);/* Call this last ! */
	soundStream.setup(this,2,2, sampleRate, initialBufferSize, 4);
	//soundStream.setOutput(this);

	// Determinação de curvas
	int bins =  fftSize/2;
	CurvaItu = new float[bins];
	CurvaA = new float[bins];
	CurvaB = new float[bins];
	CurvaC = new float[bins];
	CurvaD = new float[bins];
	for (int i=0; i<bins; i++){
		float f = sampleRate/bins;
		CurvaItu[i] = Ritu(i);
		CurvaA[i] = RA_db(i);
		CurvaB[i] = RB(i);
		CurvaC[i] = RC(i);
		CurvaD[i] = RD(i);
	}

	// Gravação
	wavWriter.setFormat(1, sampleRate, 16);  
	IsRecording = false;
}
Пример #24
0
void gauss_seidel ( int nx, int ny, int nz, double u[], double f[], double tol, int it_max,
              double xlo, double ylo, double zlo,
              double xhi, double yhi, double zhi, int io_interval, char rb [])
{

    double ax, ay, az, d;
    double dx, dy, dz, rem;
    double update_norm, unew;
    int i, it, j, k, it_used = it_max;
    double *u_old, diff;
    double omega;

    /* Initialize the coefficients.  */

    dx =  (xhi - xlo) / ( double ) ( nx - 1 );
    dy =  (yhi - ylo) / ( double ) ( ny - 1 );
    dz =  (zhi - zlo) / ( double ) ( nz - 1 );

    ax =   1.0 / (dx * dx);
    ay =   1.0 / (dy * dy);
    az =   1.0 / (dz * dz);
    d  = - 2.0 / (dx * dx)  - 2.0 / (dy * dy) -2.0 / (dz * dz);
    omega = 1;

    for ( it = 1; it <= it_max; it++ ) {
        update_norm = 0.0;

     /* Compute stencil, and update.  bcs already in u. only update interior of domain */
      for ( k = 1; k < nz-1; k++ ) {
        for ( j = 1; j < ny-1; j++ ) {
            for ( i = 1; i < nx-1; i++ ) {
		if('r' == RB(i,j,k)){
			rem = U(i,j,k);
                	U(i,j,k) = (F(i,j,k) -
                        	( ax * ( U(i-1,j,k) + U(i+1,j,k) ) +
                        	  ay * ( U(i,j-1,k) + U(i,j+1,k) ) +
                        	  az * ( U(i,j,k-1) + U(i,j,k+1) ) ) ) / d;

                	diff = ABS(U(i,j,k)-rem);
                
			//update_norm = update_norm + diff*diff;  /* using 2 norm */

                	if (diff > update_norm){ /* using max norm */
                	    update_norm = diff;
                	  }

               }
            } /* end for i */
        } /* end for j */
      } /* end for k */

      for ( k = 1; k < nz-1; k++ ) {
        for ( j = 1; j < ny-1; j++ ) {
            for ( i = 1; i < nx-1; i++ ) {
		if('b' == RB(i,j,k)){
			rem = U(i,j,k);
                	U(i,j,k) = (F(i,j,k) -
                        	( ax * ( U(i-1,j,k) + U(i+1,j,k) ) +
                        	  ay * ( U(i,j-1,k) + U(i,j+1,k) ) +
                        	  az * ( U(i,j,k-1) + U(i,j,k+1) ) ) ) / d;

                	diff = ABS(U(i,j,k)-rem);
                
			//update_norm = update_norm + diff*diff;  /* using 2 norm */

                	if (diff > update_norm){ /* using max norm */
                	    update_norm = diff;
                	  }

               }
            } /* end for i */
        } /* end for j */
      } /* end for k */

        if (0 == it% io_interval) 
            printf ( " iteration  %5d   norm update %14.4e\n", it, update_norm );

        if ( update_norm <= tol ) {
          it_used = it;
          break;
        }

    } /* end for it iterations */
    printf ( " Final iteration  %5d   norm update %14.6e\n", it_used, update_norm );

    return;
}
Пример #25
0
Файл: lvm.c Проект: zapline/zlib
static void Arith (lua_State *L, StkId ra, const TValue *rb,
                   const TValue *rc, TMS op) {
  TValue tempb, tempc;
  const TValue *b, *c;
#if LUA_REFCOUNT
  luarc_newvalue(&tempb);
  luarc_newvalue(&tempc);
  if ((b = luaV_tonumber(L, rb, &tempb)) != NULL &&
      (c = luaV_tonumber(L, rc, &tempc)) != NULL) {
#else
  if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
      (c = luaV_tonumber(rc, &tempc)) != NULL) {
#endif /* LUA_REFCOUNT */
    lua_Number nb = nvalue(b), nc = nvalue(c);
#if LUA_REFCOUNT
    luarc_cleanvalue(&tempb);
    luarc_cleanvalue(&tempc);
#endif /* LUA_REFCOUNT */
    switch (op) {
      case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
      case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
      case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
      case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
      case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
      case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
      case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
      default: lua_assert(0); break;
    }
  }
#if LUA_REFCOUNT
  else if (!call_binTM(L, rb, rc, ra, op)) {
    luarc_cleanvalue(&tempb);
    luarc_cleanvalue(&tempc);
    luaG_aritherror(L, rb, rc);
  }
#else
  else if (!call_binTM(L, rb, rc, ra, op))
    luaG_aritherror(L, rb, rc);
#endif /* LUA_REFCOUNT */
}



/*
** some macros for common tasks in `luaV_execute'
*/

#define runtime_check(L, c)	{ if (!(c)) break; }

#define RA(i)	(base+GETARG_A(i))
/* to be used after possible stack reallocation */
#define RB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
#define RC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
#define RKB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
	ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
#define RKC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
	ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
#define KBx(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i))


#define dojump(L,pc,i)	{(pc) += (i); luai_threadyield(L);}


#define Protect(x)	{ L->savedpc = pc; {x;}; base = L->base; }


#define arith_op(op,tm) { \
        TValue *rb = RKB(i); \
        TValue *rc = RKC(i); \
        if (ttisnumber(rb) && ttisnumber(rc)) { \
          lua_Number nb = nvalue(rb), nc = nvalue(rc); \
          setnvalue(ra, op(nb, nc)); \
        } \
        else \
          Protect(Arith(L, ra, rb, rc, tm)); \
      }

#if LUA_BITFIELD_OPS

#define bit_op(op) { \
        TValue *rb = RKB(i); \
        TValue *rc = RKC(i); \
        if (ttisnumber(rb) && ttisnumber(rc)) { \
          unsigned int nb = (unsigned int)nvalue(rb), nc = (unsigned int)nvalue(rc); \
          setnvalue(ra, nb op nc); \
        } \
        else \
          luaG_aritherror(L, rb, rc); \
      }

#endif /* LUA_BITFIELD_OPS */



void luaV_execute (lua_State *L, int nexeccalls) {
  LClosure *cl;
  StkId base;
  TValue *k;
  const Instruction *pc;
 reentry:  /* entry point */
  lua_assert(isLua(L->ci));
  pc = L->savedpc;
  cl = &clvalue(L->ci->func)->l;
  base = L->base;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L, pc);
      if (L->status == LUA_YIELD) {  /* did hook yield? */
        L->savedpc = pc - 1;
        return;
      }
      base = L->base;
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        continue;
      }
      case OP_LOADNIL: {
        TValue *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_GETGLOBAL: {
        TValue g;
        TValue *rb = KBx(i);
#if LUA_REFCOUNT
        sethvalue2n(L, &g, cl->env);
#else
        sethvalue(L, &g, cl->env);
#endif /* LUA_REFCOUNT */
        lua_assert(ttisstring(rb));
        Protect(luaV_gettable(L, &g, rb, ra));
#if LUA_REFCOUNT
		setnilvalue(&g);
#endif /* LUA_REFCOUNT */
        continue;
      }
      case OP_GETTABLE: {
        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
        continue;
      }
      case OP_SETGLOBAL: {
        TValue g;
#if LUA_REFCOUNT
        sethvalue2n(L, &g, cl->env);
#else
        sethvalue(L, &g, cl->env);
#endif /* LUA_REFCOUNT */
        lua_assert(ttisstring(KBx(i)));
        Protect(luaV_settable(L, &g, KBx(i), ra));
#if LUA_REFCOUNT
		setnilvalue(&g);
#endif /* LUA_REFCOUNT */
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
        Protect(luaC_checkGC(L));
        continue;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        setobjs2s(L, ra+1, rb);
        Protect(luaV_gettable(L, rb, RKC(i), ra));
        continue;
      }
      case OP_ADD: {
        arith_op(luai_numadd, TM_ADD);
        continue;
      }
      case OP_SUB: {
        arith_op(luai_numsub, TM_SUB);
        continue;
      }
      case OP_MUL: {
        arith_op(luai_nummul, TM_MUL);
        continue;
      }
      case OP_DIV: {
        arith_op(luai_numdiv, TM_DIV);
        continue;
      }
      case OP_MOD: {
        arith_op(luai_nummod, TM_MOD);
        continue;
      }
      case OP_POW: {
        arith_op(luai_numpow, TM_POW);
        continue;
      }
      case OP_UNM: {
        TValue *rb = RB(i);
        if (ttisnumber(rb)) {
          lua_Number nb = nvalue(rb);
          setnvalue(ra, luai_numunm(nb));
        }
        else {
          Protect(Arith(L, ra, rb, rb, TM_UNM));
        }
        continue;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        continue;
      }
#if LUA_BITFIELD_OPS
      case OP_BAND: {
        bit_op(&);
        continue;
      }
      case OP_BOR: {
        bit_op(|);
        continue;
      }
      case OP_BXOR: {
        bit_op(^);
        continue;
      }
      case OP_BSHL: {
        bit_op(<<);
        continue;
      }
      case OP_BSHR: {
        bit_op(>>);
        continue;
      }
#endif /* LUA_BITFIELD_OPS */
      case OP_LEN: {
        const TValue *rb = RB(i);
        switch (ttype(rb)) {
          case LUA_TTABLE: {
            setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
            break;
          }
          case LUA_TSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
#if LUA_WIDESTRING
          case LUA_TWSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
#endif /* LUA_WIDESTRING */
          default: {  /* try metamethod */
            Protect(
              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
                luaG_typeerror(L, rb, "get length of");
            )
          }
        }
        continue;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
        setobjs2s(L, RA(i), base+b);
        continue;
      }
      case OP_JMP: {
        dojump(L, pc, GETARG_sBx(i));
        continue;
      }
      case OP_EQ: {
        TValue *rb = RKB(i);
        TValue *rc = RKC(i);
        Protect(
          if (equalobj(L, rb, rc) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LT: {
        Protect(
          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LE: {
        Protect(
          if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
Пример #26
0
static int
get_active_uniform
  (struct rb_context* ctxt,
   struct rb_program* program,
   GLuint index,
   GLsizei bufsize,
   GLchar* buffer,
   struct rb_uniform** out_uniform)
{
  struct rb_uniform* uniform = NULL;
  GLsizei uniform_namelen = 0;
  GLint uniform_size = 0;
  GLenum uniform_type;
  int err = 0;

  if(!ctxt
  || !program
  || !out_uniform
  || bufsize < 0
  || (bufsize && !buffer))
    goto error;

  OGL(GetActiveUniform
      (program->name,
       index,
       bufsize,
       &uniform_namelen,
       &uniform_size,
       &uniform_type,
       buffer));

  uniform = MEM_CALLOC(ctxt->allocator, 1, sizeof(struct rb_uniform));
  if(!uniform)
    goto error;
  ref_init(&uniform->ref);
  RB(context_ref_get(ctxt));
  uniform->ctxt = ctxt;
  RB(program_ref_get(program));
  uniform->program = program;
  uniform->index = index;
  uniform->type = uniform_type;
  uniform->set = get_uniform_setter(uniform_type);

  if(buffer) {
    /* Add 1 to namelen <=> include the null character. */
    ++uniform_namelen;

    uniform->name = MEM_ALLOC
      (ctxt->allocator, sizeof(char) * uniform_namelen);
    if(!uniform->name)
      goto error;

    uniform->name = strncpy(uniform->name, buffer, uniform_namelen);
    uniform->location = OGL(GetUniformLocation(program->name, uniform->name));
  }

exit:
  *out_uniform = uniform;
  return err;

error:
  if(uniform) {
    RB(uniform_ref_put(uniform));
    uniform = NULL;
  }
  err = -1;
  goto exit;
}
Пример #27
0
int
rb_get_uniforms
  (struct rb_context* ctxt,
   struct rb_program* prog,
   size_t* out_nb_uniforms,
   struct rb_uniform* dst_uniform_list[])
{
  GLchar* uniform_buffer = NULL;
  int uniform_buflen = 0;
  int nb_uniforms = 0;
  int uniform_id = 0;
  int err = 0;

  if(!ctxt || !prog || !out_nb_uniforms)
    goto error;

  if(!prog->is_linked)
    goto error;

  OGL(GetProgramiv(prog->name, GL_ACTIVE_UNIFORMS, &nb_uniforms));
  assert(nb_uniforms >= 0);

  if(dst_uniform_list) {
      OGL(GetProgramiv
        (prog->name, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniform_buflen));
    uniform_buffer = MEM_ALLOC
      (ctxt->allocator, sizeof(GLchar) * uniform_buflen);
    if(!uniform_buffer)
      goto error;

    for(uniform_id = 0; uniform_id < nb_uniforms; ++uniform_id) {
      struct rb_uniform* uniform = NULL;

      err = get_active_uniform
        (ctxt, prog, uniform_id, uniform_buflen, uniform_buffer, &uniform);
      if(err != 0)
        goto error;

      dst_uniform_list[uniform_id] = uniform;
    }
  }

exit:
  if(uniform_buffer)
    MEM_FREE(ctxt->allocator, uniform_buffer);
  if(out_nb_uniforms)
    *out_nb_uniforms = nb_uniforms;
  return err;

error:
  if(dst_uniform_list) {
    /* NOTE: uniform_id <=> nb uniforms in dst_uniform_list; */
    int i = 0;
    for(i = 0; i < uniform_id; ++i) {
      RB(uniform_ref_put(dst_uniform_list[i]));
      dst_uniform_list[i] = NULL;
    }
  }
  nb_uniforms = 0;
  err = -1;
  goto exit;
}
Пример #28
0
int crl2pkcs7_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    PKCS7 *p7 = NULL;
    PKCS7_SIGNED *p7s = NULL;
    STACK_OF(OPENSSL_STRING) *certflst = NULL;
    STACK_OF(X509) *cert_stack = NULL;
    STACK_OF(X509_CRL) *crl_stack = NULL;
    X509_CRL *crl = NULL;
    char *infile = NULL, *outfile = NULL, *prog, *certfile;
    int i = 0, informat = FORMAT_PEM, outformat = FORMAT_PEM, ret = 1, nocrl =
        0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, crl2pkcs7_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(crl2pkcs7_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_NOCRL:
            nocrl = 1;
            break;
        case OPT_CERTFILE:
            if ((certflst == NULL)
                && (certflst = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            if (!sk_OPENSSL_STRING_push(certflst, *(++argv))) {
                sk_OPENSSL_STRING_free(certflst);
                goto end;
            }
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (!app_load_modules(NULL))
        goto end;

    if (!nocrl) {
        in = bio_open_default(infile, RB(informat));
        if (in == NULL)
            goto end;

        if (informat == FORMAT_ASN1)
            crl = d2i_X509_CRL_bio(in, NULL);
        else if (informat == FORMAT_PEM)
            crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
        if (crl == NULL) {
            BIO_printf(bio_err, "unable to load CRL\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if ((p7 = PKCS7_new()) == NULL)
        goto end;
    if ((p7s = PKCS7_SIGNED_new()) == NULL)
        goto end;
    p7->type = OBJ_nid2obj(NID_pkcs7_signed);
    p7->d.sign = p7s;
    p7s->contents->type = OBJ_nid2obj(NID_pkcs7_data);

    if (!ASN1_INTEGER_set(p7s->version, 1))
        goto end;
    if ((crl_stack = sk_X509_CRL_new_null()) == NULL)
        goto end;
    p7s->crl = crl_stack;
    if (crl != NULL) {
        sk_X509_CRL_push(crl_stack, crl);
        crl = NULL;             /* now part of p7 for OPENSSL_freeing */
    }

    if ((cert_stack = sk_X509_new_null()) == NULL)
        goto end;
    p7s->cert = cert_stack;

    if (certflst)
        for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) {
            certfile = sk_OPENSSL_STRING_value(certflst, i);
            if (add_certs_from_file(cert_stack, certfile) < 0) {
                BIO_printf(bio_err, "error loading certificates\n");
                ERR_print_errors(bio_err);
                goto end;
            }
        }

    sk_OPENSSL_STRING_free(certflst);

    out = bio_open_default(outfile, WB(outformat));
    if (out == NULL)
        goto end;

    if (outformat == FORMAT_ASN1)
        i = i2d_PKCS7_bio(out, p7);
    else if (outformat == FORMAT_PEM)
        i = PEM_write_bio_PKCS7(out, p7);
    if (!i) {
        BIO_printf(bio_err, "unable to write pkcs7 object\n");
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;
 end:
    BIO_free(in);
    BIO_free_all(out);
    PKCS7_free(p7);
    X509_CRL_free(crl);

    return (ret);
}
Пример #29
0
void luaV_execute (lua_State *L, int nexeccalls) {
  LClosure *cl;
  StkId base;
  TValue *k;
  const Instruction *pc;
 reentry:  /* entry point */
  lua_assert(isLua(L->ci));
  pc = L->savedpc;
  cl = &clvalue(L->ci->func)->l;
  base = L->base;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L, pc);
      if (L->status == LUA_YIELD) {  /* did hook yield? */
        L->savedpc = pc - 1;
        return;
      }
      base = L->base;
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    ra = RA(i);
    lua_assert(base == L->base && L->base == L->ci->base);
    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(L, ra, RB(i));
        continue;
      }
      case OP_LOADK: {
        setobj2s(L, ra, KBx(i));
        continue;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        continue;
      }
      case OP_LOADNIL: {
        TValue *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        continue;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(L, ra, cl->upvals[b]->v);
        continue;
      }
      case OP_GETGLOBAL: {
        TValue g;
        TValue *rb = KBx(i);
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(rb));
        Protect(luaV_gettable(L, &g, rb, ra));
        continue;
      }
      case OP_GETTABLE: {
        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
        continue;
      }
      case OP_SETGLOBAL: {
        TValue g;
        sethvalue(L, &g, cl->env);
        lua_assert(ttisstring(KBx(i)));
        Protect(luaV_settable(L, &g, KBx(i), ra));
        continue;
      }
      case OP_SETUPVAL: {
        UpVal *uv = cl->upvals[GETARG_B(i)];
        setobj(L, uv->v, ra);
        luaC_barrier(L, uv, ra);
        continue;
      }
      case OP_SETTABLE: {
        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
        continue;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
        Protect(luaC_checkGC(L));
        continue;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        setobjs2s(L, ra+1, rb);
        Protect(luaV_gettable(L, rb, RKC(i), ra));
        continue;
      }
      case OP_ADD: {
        arith_op(luai_numadd, TM_ADD);
        continue;
      }
      case OP_SUB: {
        arith_op(luai_numsub, TM_SUB);
        continue;
      }
      case OP_MUL: {
        arith_op(luai_nummul, TM_MUL);
        continue;
      }
      case OP_DIV: {
        arith_op(luai_numdiv, TM_DIV);
        continue;
      }
      case OP_MOD: {
        arith_op(luai_nummod, TM_MOD);
        continue;
      }
      case OP_POW: {
        arith_op(luai_numpow, TM_POW);
        continue;
      }
      case OP_UNM: {
        TValue *rb = RB(i);
        if (ttisnumber(rb)) {
          lua_Number nb = nvalue(rb);
          setnvalue(ra, luai_numunm(nb));
        }
        else {
          Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
        }
        continue;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        continue;
      }
      case OP_LEN: {
        const TValue *rb = RB(i);
        switch (ttype(rb)) {
          case LUA_TTABLE: {
            setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
            break;
          }
          case LUA_TSTRING: {
            setnvalue(ra, cast_num(tsvalue(rb)->len));
            break;
          }
          default: {  /* try metamethod */
            Protect(
              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
                luaG_typeerror(L, rb, "get length of");
            )
          }
        }
        continue;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
        setobjs2s(L, RA(i), base+b);
        continue;
      }
      case OP_JMP: {
        dojump(L, pc, GETARG_sBx(i));
        continue;
      }
      case OP_EQ: {
        TValue *rb = RKB(i);
        TValue *rc = RKC(i);
        Protect(
          if (equalobj(L, rb, rc) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LT: {
        Protect(
          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
      case OP_LE: {
        Protect(
          if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
            dojump(L, pc, GETARG_sBx(*pc));
        )
        pc++;
        continue;
      }
Пример #30
0
StkId luaV_execute (lua_State *L) {
  LClosure *cl;
  TObject *k;
  const Instruction *pc;
 callentry:  /* entry point when calling new functions */
  L->ci->u.l.pc = &pc;
  if (L->hookmask & LUA_MASKCALL)
    luaD_callhook(L, LUA_HOOKCALL, -1);
 retentry:  /* entry point when returning to old functions */
  lua_assert(L->ci->state == CI_SAVEDPC ||
             L->ci->state == (CI_SAVEDPC | CI_CALLING));
  L->ci->state = CI_HASFRAME;  /* activate frame */
  pc = L->ci->u.l.savedpc;
  cl = &clvalue(L->base - 1)->l;
  k = cl->p->k;
  /* main loop of interpreter */
  for (;;) {
    const Instruction i = *pc++;
    StkId base, ra;
    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
      traceexec(L);
      if (L->ci->state & CI_YIELD) {  /* did hook yield? */
        L->ci->u.l.savedpc = pc - 1;
        L->ci->state = CI_YIELD | CI_SAVEDPC;
        return NULL;
      }
    }
    /* warning!! several calls may realloc the stack and invalidate `ra' */
    base = L->base;
    ra = RA(i);
    lua_assert(L->ci->state & CI_HASFRAME);
    lua_assert(base == L->ci->base);
    lua_assert(L->top <= L->stack + L->stacksize && L->top >= base);
    lua_assert(L->top == L->ci->top ||
         GET_OPCODE(i) == OP_CALL ||   GET_OPCODE(i) == OP_TAILCALL ||
         GET_OPCODE(i) == OP_RETURN || GET_OPCODE(i) == OP_SETLISTO);
    switch (GET_OPCODE(i)) {
      case OP_MOVE: {
        setobjs2s(ra, RB(i));
        break;
      }
      case OP_LOADK: {
        setobj2s(ra, KBx(i));
        break;
      }
      case OP_LOADBOOL: {
        setbvalue(ra, GETARG_B(i));
        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
        break;
      }
      case OP_LOADNIL: {
        TObject *rb = RB(i);
        do {
          setnilvalue(rb--);
        } while (rb >= ra);
        break;
      }
      case OP_GETUPVAL: {
        int b = GETARG_B(i);
        setobj2s(ra, cl->upvals[b]->v);
        break;
      }
      case OP_GETGLOBAL: {
        TObject *rb = KBx(i);
        const TObject *v;
        lua_assert(ttisstring(rb) && ttistable(&cl->g));
        v = luaH_getstr(hvalue(&cl->g), tsvalue(rb));
        if (!ttisnil(v)) { setobj2s(ra, v); }
        else
          setobj2s(XRA(i), luaV_index(L, &cl->g, rb, 0));
        break;
      }
      case OP_GETTABLE: {
        StkId rb = RB(i);
        TObject *rc = RKC(i);
        if (ttistable(rb)) {
          const TObject *v = luaH_get(hvalue(rb), rc);
          if (!ttisnil(v)) { setobj2s(ra, v); }
          else
            setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
        }
        else
          setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
        break;
      }
      case OP_SETGLOBAL: {
        lua_assert(ttisstring(KBx(i)) && ttistable(&cl->g));
        luaV_settable(L, &cl->g, KBx(i), ra);
        break;
      }
      case OP_SETUPVAL: {
        int b = GETARG_B(i);
        setobj(cl->upvals[b]->v, ra);  /* write barrier */
        break;
      }
      case OP_SETTABLE: {
        luaV_settable(L, ra, RKB(i), RKC(i));
        break;
      }
      case OP_NEWTABLE: {
        int b = GETARG_B(i);
        b = fb2int(b);
        sethvalue(ra, luaH_new(L, b, GETARG_C(i)));
        luaC_checkGC(L);
        break;
      }
      case OP_SELF: {
        StkId rb = RB(i);
        TObject *rc = RKC(i);
        runtime_check(L, ttisstring(rc));
        setobjs2s(ra+1, rb);
        if (ttistable(rb)) {
          const TObject *v = luaH_getstr(hvalue(rb), tsvalue(rc));
          if (!ttisnil(v)) { setobj2s(ra, v); }
          else
            setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
        }
        else
          setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
        break;
      }
      case OP_ADD: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) + nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_ADD);
        break;
      }
      case OP_SUB: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) - nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_SUB);
        break;
      }
      case OP_MUL: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) * nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_MUL);
        break;
      }
      case OP_DIV: {
        TObject *rb = RKB(i);
        TObject *rc = RKC(i);
        if (ttisnumber(rb) && ttisnumber(rc)) {
          setnvalue(ra, nvalue(rb) / nvalue(rc));
        }
        else
          Arith(L, ra, rb, rc, TM_DIV);
        break;
      }
      case OP_POW: {
        Arith(L, ra, RKB(i), RKC(i), TM_POW);
        break;
      }
      case OP_UNM: {
        const TObject *rb = RB(i);
        TObject temp;
        if (tonumber(rb, &temp)) {
          setnvalue(ra, -nvalue(rb));
        }
        else {
          setnilvalue(&temp);
          if (!call_binTM(L, RB(i), &temp, ra, TM_UNM))
            luaG_aritherror(L, RB(i), &temp);
        }
        break;
      }
      case OP_NOT: {
        int res = l_isfalse(RB(i));  /* next assignment may change this value */
        setbvalue(ra, res);
        break;
      }
      case OP_CONCAT: {
        int b = GETARG_B(i);
        int c = GETARG_C(i);
        luaV_concat(L, c-b+1, c);  /* may change `base' (and `ra') */
        base = L->base;
        setobjs2s(RA(i), base+b);
        luaC_checkGC(L);
        break;
      }
      case OP_JMP: {
        dojump(pc, GETARG_sBx(i));
        break;
      }
      case OP_EQ: {
        if (equalobj(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_LT: {
        if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_LE: {
        if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
        else dojump(pc, GETARG_sBx(*pc) + 1);
        break;
      }
      case OP_TEST: {
        TObject *rb = RB(i);
        if (l_isfalse(rb) == GETARG_C(i)) pc++;
        else {
          setobjs2s(ra, rb);
          dojump(pc, GETARG_sBx(*pc) + 1);
        }
        break;
      }
      case OP_CALL:
      case OP_TAILCALL: {
        StkId firstResult;
        int b = GETARG_B(i);
        int nresults;
        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
        nresults = GETARG_C(i) - 1;
        firstResult = luaD_precall(L, ra);
        if (firstResult) {
          if (firstResult > L->top) {  /* yield? */
            lua_assert(L->ci->state == (CI_C | CI_YIELD));
            (L->ci - 1)->u.l.savedpc = pc;
            (L->ci - 1)->state = CI_SAVEDPC;
            return NULL;
          }
          /* it was a C function (`precall' called it); adjust results */
          luaD_poscall(L, nresults, firstResult);
          if (nresults >= 0) L->top = L->ci->top;
        }
        else {  /* it is a Lua function */
          if (GET_OPCODE(i) == OP_CALL) {  /* regular call? */
            (L->ci-1)->u.l.savedpc = pc;  /* save `pc' to return later */
            (L->ci-1)->state = (CI_SAVEDPC | CI_CALLING);
          }
          else {  /* tail call: put new frame in place of previous one */
            int aux;
            base = (L->ci - 1)->base;  /* `luaD_precall' may change the stack */
            ra = RA(i);
            if (L->openupval) luaF_close(L, base);
            for (aux = 0; ra+aux < L->top; aux++)  /* move frame down */
              setobjs2s(base+aux-1, ra+aux);
            (L->ci - 1)->top = L->top = base+aux;  /* correct top */
            lua_assert(L->ci->state & CI_SAVEDPC);
            (L->ci - 1)->u.l.savedpc = L->ci->u.l.savedpc;
            (L->ci - 1)->u.l.tailcalls++;  /* one more call lost */
            (L->ci - 1)->state = CI_SAVEDPC;
            L->ci--;  /* remove new frame */
            L->base = L->ci->base;
          }
          goto callentry;
        }
        break;
      }
      case OP_RETURN: {
        CallInfo *ci = L->ci - 1;  /* previous function frame */
        int b = GETARG_B(i);
        if (b != 0) L->top = ra+b-1;
        lua_assert(L->ci->state & CI_HASFRAME);
        if (L->openupval) luaF_close(L, base);
        L->ci->state = CI_SAVEDPC;  /* deactivate current function */
        L->ci->u.l.savedpc = pc;
        /* previous function was running `here'? */
        if (!(ci->state & CI_CALLING)) {
          lua_assert((ci->state & CI_C) || ci->u.l.pc != &pc);
          return ra;  /* no: return */
        }
        else {  /* yes: continue its execution */
          int nresults;
          lua_assert(ci->u.l.pc == &pc &&
                     ttisfunction(ci->base - 1) &&
                     (ci->state & CI_SAVEDPC));
          lua_assert(GET_OPCODE(*(ci->u.l.savedpc - 1)) == OP_CALL);
          nresults = GETARG_C(*(ci->u.l.savedpc - 1)) - 1;
          luaD_poscall(L, nresults, ra);
          if (nresults >= 0) L->top = L->ci->top;
          goto retentry;
        }
      }
      case OP_FORLOOP: {
        lua_Number step, idx, limit;
        const TObject *plimit = ra+1;
        const TObject *pstep = ra+2;
        if (!ttisnumber(ra))
          luaG_runerror(L, "`for' initial value must be a number");
        if (!tonumber(plimit, ra+1))
          luaG_runerror(L, "`for' limit must be a number");
        if (!tonumber(pstep, ra+2))
          luaG_runerror(L, "`for' step must be a number");
        step = nvalue(pstep);
        idx = nvalue(ra) + step;  /* increment index */
        limit = nvalue(plimit);
        if (step > 0 ? idx <= limit : idx >= limit) {
          dojump(pc, GETARG_sBx(i));  /* jump back */
          chgnvalue(ra, idx);  /* update index */
        }
        break;
      }
      case OP_TFORLOOP: {
        int nvar = GETARG_C(i) + 1;
        StkId cb = ra + nvar + 2;  /* call base */
        setobjs2s(cb, ra);
        setobjs2s(cb+1, ra+1);
        setobjs2s(cb+2, ra+2);
        L->top = cb+3;  /* func. + 2 args (state and index) */
        luaD_call(L, cb, nvar);
        L->top = L->ci->top;
        ra = XRA(i) + 2;  /* final position of first result */
        cb = ra + nvar;
        do {  /* move results to proper positions */
          nvar--;
          setobjs2s(ra+nvar, cb+nvar);
        } while (nvar > 0);
        if (ttisnil(ra))  /* break loop? */
          pc++;  /* skip jump (break loop) */
        else
          dojump(pc, GETARG_sBx(*pc) + 1);  /* jump back */
        break;
      }
      case OP_TFORPREP: {  /* for compatibility only */
        if (ttistable(ra)) {
          setobjs2s(ra+1, ra);
          setobj2s(ra, luaH_getstr(hvalue(gt(L)), luaS_new(L, "next")));
        }
        dojump(pc, GETARG_sBx(i));
        break;
      }
      case OP_SETLIST:
      case OP_SETLISTO: {
        int bc;
        int n;
        Table *h;
        runtime_check(L, ttistable(ra));
        h = hvalue(ra);
        bc = GETARG_Bx(i);
        if (GET_OPCODE(i) == OP_SETLIST)
          n = (bc&(LFIELDS_PER_FLUSH-1)) + 1;
        else {
          n = L->top - ra - 1;
          L->top = L->ci->top;
        }
        bc &= ~(LFIELDS_PER_FLUSH-1);  /* bc = bc - bc%FPF */
        for (; n > 0; n--)
          setobj2t(luaH_setnum(L, h, bc+n), ra+n);  /* write barrier */
        break;
      }
      case OP_CLOSE: {
        luaF_close(L, ra);
        break;
      }
      case OP_CLOSURE: {
        Proto *p;
        Closure *ncl;
        int nup, j;
        p = cl->p->p[GETARG_Bx(i)];
        nup = p->nups;
        ncl = luaF_newLclosure(L, nup, &cl->g);
        ncl->l.p = p;
        for (j=0; j<nup; j++, pc++) {
          if (GET_OPCODE(*pc) == OP_GETUPVAL)
            ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
          else {
            lua_assert(GET_OPCODE(*pc) == OP_MOVE);
            ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
          }
        }
        setclvalue(ra, ncl);
        luaC_checkGC(L);
        break;
      }
    }
  }
}