static int VibeOSKernelProcessData(void* data)
{
    int i;
    int nActuatorNotPlaying = 0;

    for (i = 0; i < NUM_ACTUATORS; i++)
    {
        actuator_samples_buffer *pCurrentActuatorSample = &(g_SamplesBuffer[i]);

        if (-1 == pCurrentActuatorSample->nIndexPlayingBuffer)
        {
            nActuatorNotPlaying++;
            if ((NUM_ACTUATORS == nActuatorNotPlaying) && ((++g_nWatchdogCounter) > WATCHDOG_TIMEOUT))
            {
                VibeInt8 cZero[1] = {0};

                /* Nothing to play for all actuators, turn off the timer when we reach the watchdog tick count limit */
                ImmVibeSPI_ForceOut_SetSamples(i, 8, 1, cZero);
                ImmVibeSPI_ForceOut_AmpDisable(i);
                VibeOSKernelLinuxStopTimer();

                /* Reset watchdog counter */
                g_nWatchdogCounter = 0;
            }
        }
        else
        {
            /* Play the current buffer */
            if (VIBE_E_FAIL == ImmVibeSPI_ForceOut_SetSamples(
                pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nActuatorIndex,
		pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nBitDepth,
		pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nBufferSize,
                pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].dataBuffer))
            {
                /* VIBE_E_FAIL means NAK has been handled. Schedule timer to restart 5 ms from now */
                hrtimer_forward_now(&g_tspTimer, g_ktFiveMs);
            }

            pCurrentActuatorSample->nIndexOutputValue += pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nBufferSize;

            if (pCurrentActuatorSample->nIndexOutputValue >= pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nBufferSize)
            {
                /* Reach the end of the current buffer */
                pCurrentActuatorSample->actuatorSamples[(int)pCurrentActuatorSample->nIndexPlayingBuffer].nBufferSize = 0;

                /* Switch buffer */
                (pCurrentActuatorSample->nIndexPlayingBuffer) ^= 1;
                pCurrentActuatorSample->nIndexOutputValue = 0;

                /* Finished playing, disable amp for actuator (i) */
                if (g_bStopRequested)
                {
                    pCurrentActuatorSample->nIndexPlayingBuffer = -1;
		    ImmVibeSPI_ForceOut_AmpDisable(i);
                }
            }
        }
    }

    /* If finished playing, stop timer */
    if (g_bStopRequested)
    {
        VibeOSKernelLinuxStopTimer();

        /* Reset watchdog counter */
        g_nWatchdogCounter = 0;

        if (VibeSemIsLocked(&g_hMutex)) up(&g_hMutex);
        return 1;   /* tell the caller this is the last iteration */
    }

    return 0;
}
Beispiel #2
0
int cifs_setxattr(struct dentry * direntry, const char * ea_name,
        const void * ea_value, size_t value_size, int flags)
{
	int rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
	int xid;
	struct cifs_sb_info *cifs_sb;
	struct cifsTconInfo *pTcon;
	struct super_block * sb;
	char * full_path;

	if(direntry == NULL)
		return -EIO;
	if(direntry->d_inode == NULL)
		return -EIO;
	sb = direntry->d_inode->i_sb;
	if(sb == NULL)
		return -EIO;
	xid = GetXid();

	cifs_sb = CIFS_SB(sb);
	pTcon = cifs_sb->tcon;

	down(&sb->s_vfs_rename_sem);
	full_path = build_path_from_dentry(direntry);
	up(&sb->s_vfs_rename_sem);
	if(full_path == NULL) {
		FreeXid(xid);
		return -ENOMEM;
	}
	/* return dos attributes as pseudo xattr */
	/* return alt name if available as pseudo attr */

	/* if proc/fs/cifs/streamstoxattr is set then
		search server for EAs or streams to 
		returns as xattrs */
	if(value_size > MAX_EA_VALUE_SIZE) {
		cFYI(1,("size of EA value too large"));
		if(full_path)
			kfree(full_path);
		FreeXid(xid);
		return -EOPNOTSUPP;
	}

	if(ea_name == NULL) {
		cFYI(1,("Null xattr names not supported"));
	} else if(strncmp(ea_name,CIFS_XATTR_USER_PREFIX,5) == 0) {
		if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
			goto set_ea_exit;
		if(strncmp(ea_name,CIFS_XATTR_DOS_ATTRIB,14) == 0) {
			cFYI(1,("attempt to set cifs inode metadata"));
		}
		ea_name += 5; /* skip past user. prefix */
		rc = CIFSSMBSetEA(xid,pTcon,full_path,ea_name,ea_value,
			(__u16)value_size, cifs_sb->local_nls);
	} else if(strncmp(ea_name, CIFS_XATTR_OS2_PREFIX,4) == 0) {
		if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
			goto set_ea_exit;

		ea_name += 4; /* skip past os2. prefix */
		rc = CIFSSMBSetEA(xid,pTcon,full_path,ea_name,ea_value,
			(__u16)value_size, cifs_sb->local_nls);
	} else {
		int temp; 
		temp = strncmp(ea_name,POSIX_ACL_XATTR_ACCESS,
			strlen(POSIX_ACL_XATTR_ACCESS));
		if (temp == 0) {
#ifdef CONFIG_CIFS_POSIX
			rc = CIFSSMBSetPosixACL(xid, pTcon,full_path,ea_value,
				(const int)value_size, ACL_TYPE_ACCESS,
				cifs_sb->local_nls);
			cFYI(1,("set POSIX ACL rc %d",rc));
#else
			cFYI(1,("set POSIX ACL not supported"));
#endif
		} else if(strncmp(ea_name,POSIX_ACL_XATTR_DEFAULT,strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
			rc = CIFSSMBSetPosixACL(xid, pTcon,full_path,ea_value,
				(const int)value_size, ACL_TYPE_DEFAULT,
				cifs_sb->local_nls);
			cFYI(1,("set POSIX default ACL rc %d",rc));
#else
			cFYI(1,("set default POSIX ACL not supported"));
#endif
		} else {
			cFYI(1,("illegal xattr request %s (only user namespace supported)",ea_name));
		  /* BB what if no namespace prefix? */
		  /* Should we just pass them to server, except for 
		  system and perhaps security prefixes? */
		}
	}

set_ea_exit:
	if (full_path)
		kfree(full_path);
	FreeXid(xid);
#endif
	return rc;
}
Beispiel #3
0
void pm_set_ops(struct pm_ops * ops)
{
	down(&pm_sem);
	pm_ops = ops;
	up(&pm_sem);
}
Beispiel #4
0
/* Process one complete nfnetlink message. */
static int nfnetlink_rcv_msg(struct sk_buff *skb,
				    struct nlmsghdr *nlh, int *errp)
{
	struct nfnl_callback *nc;
	struct nfnetlink_subsystem *ss;
	int type, err = 0;

	DEBUGP("entered; subsys=%u, msgtype=%u\n",
		 NFNL_SUBSYS_ID(nlh->nlmsg_type),
		 NFNL_MSG_TYPE(nlh->nlmsg_type));

	if (security_netlink_recv(skb, CAP_NET_ADMIN)) {
		DEBUGP("missing CAP_NET_ADMIN\n");
		*errp = -EPERM;
		return -1;
	}

	/* Only requests are handled by kernel now. */
	if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) {
		DEBUGP("received non-request message\n");
		return 0;
	}

	/* All the messages must at least contain nfgenmsg */
	if (nlh->nlmsg_len < NLMSG_SPACE(sizeof(struct nfgenmsg))) {
		DEBUGP("received message was too short\n");
		return 0;
	}

	type = nlh->nlmsg_type;
	ss = nfnetlink_get_subsys(type);
	if (!ss) {
#ifdef CONFIG_KMOD
		/* don't call nfnl_shunlock, since it would reenter
		 * with further packet processing */
		up(&nfnl_sem);
		request_module("nfnetlink-subsys-%d", NFNL_SUBSYS_ID(type));
		nfnl_shlock();
		ss = nfnetlink_get_subsys(type);
		if (!ss)
#endif
			goto err_inval;
	}

	nc = nfnetlink_find_client(type, ss);
	if (!nc) {
		DEBUGP("unable to find client for type %d\n", type);
		goto err_inval;
	}

	{
		u_int16_t attr_count = 
			ss->cb[NFNL_MSG_TYPE(nlh->nlmsg_type)].attr_count;
		struct nfattr *cda[attr_count];

		memset(cda, 0, sizeof(struct nfattr *) * attr_count);
		
		err = nfnetlink_check_attributes(ss, nlh, cda);
		if (err < 0)
			goto err_inval;

		DEBUGP("calling handler\n");
		err = nc->call(nfnl, skb, nlh, cda, errp);
		*errp = err;
		return err;
	}

err_inval:
	DEBUGP("returning -EINVAL\n");
	*errp = -EINVAL;
	return -1;
}
Beispiel #5
0
static ssize_t adb_write(struct file *file, const char __user *buf,
			 size_t count, loff_t *ppos)
{
	int ret/*, i*/;
	struct adbdev_state *state = file->private_data;
	struct adb_request *req;

	if (count < 2 || count > sizeof(req->data))
		return -EINVAL;
	if (adb_controller == NULL)
		return -ENXIO;
	if (!access_ok(VERIFY_READ, buf, count))
		return -EFAULT;

	req = kmalloc(sizeof(struct adb_request),
					     GFP_KERNEL);
	if (req == NULL)
		return -ENOMEM;

	req->nbytes = count;
	req->done = adb_write_done;
	req->arg = (void *) state;
	req->complete = 0;
	
	ret = -EFAULT;
	if (copy_from_user(req->data, buf, count))
		goto out;

	atomic_inc(&state->n_pending);

	/* If a probe is in progress or we are sleeping, wait for it to complete */
	down(&adb_probe_mutex);

	/* Queries are special requests sent to the ADB driver itself */
	if (req->data[0] == ADB_QUERY) {
		if (count > 1)
			ret = do_adb_query(req);
		else
			ret = -EINVAL;
		up(&adb_probe_mutex);
	}
	/* Special case for ADB_BUSRESET request, all others are sent to
	   the controller */
	else if ((req->data[0] == ADB_PACKET)&&(count > 1)
		&&(req->data[1] == ADB_BUSRESET)) {
		ret = do_adb_reset_bus();
		up(&adb_probe_mutex);
		atomic_dec(&state->n_pending);
		if (ret == 0)
			ret = count;
		goto out;
	} else {	
		req->reply_expected = ((req->data[1] & 0xc) == 0xc);
		if (adb_controller && adb_controller->send_request)
			ret = adb_controller->send_request(req, 0);
		else
			ret = -ENXIO;
		up(&adb_probe_mutex);
	}

	if (ret != 0) {
		atomic_dec(&state->n_pending);
		goto out;
	}
	return count;

out:
	kfree(req);
	return ret;
}
Beispiel #6
0
RES Camera::_get_gizmo_geometry() const {


    Ref<SurfaceTool> surface_tool( memnew( SurfaceTool ));

    Ref<FixedMaterial> mat( memnew( FixedMaterial ));

    mat->set_parameter( FixedMaterial::PARAM_DIFFUSE,Color(1.0,0.5,1.0,0.5) );
    mat->set_line_width(4);
    mat->set_flag(Material::FLAG_DOUBLE_SIDED,true);
    mat->set_flag(Material::FLAG_UNSHADED,true);
    //mat->set_hint(Material::HINT_NO_DEPTH_DRAW,true);

    surface_tool->begin(Mesh::PRIMITIVE_LINES);
    surface_tool->set_material(mat);

    switch(mode) {

    case PROJECTION_PERSPECTIVE: {



        Vector3 side=Vector3( Math::sin(Math::deg2rad(fov)), 0, -Math::cos(Math::deg2rad(fov)) );
        Vector3 nside=side;
        nside.x=-nside.x;
        Vector3 up=Vector3(0,side.x,0);


#define ADD_TRIANGLE( m_a, m_b, m_c)\
{\
	surface_tool->add_vertex(m_a);\
	surface_tool->add_vertex(m_b);\
	surface_tool->add_vertex(m_b);\
	surface_tool->add_vertex(m_c);\
	surface_tool->add_vertex(m_c);\
	surface_tool->add_vertex(m_a);\
}

        ADD_TRIANGLE( Vector3(), side+up, side-up );
        ADD_TRIANGLE( Vector3(), nside+up, nside-up );
        ADD_TRIANGLE( Vector3(), side+up, nside+up );
        ADD_TRIANGLE( Vector3(), side-up, nside-up );

        side.x*=0.25;
        nside.x*=0.25;
        Vector3 tup( 0, up.y*3/2,side.z);
        ADD_TRIANGLE( tup, side+up, nside+up );

    }
    break;
    case PROJECTION_ORTHOGONAL: {

#define ADD_QUAD( m_a, m_b, m_c, m_d)\
{\
	surface_tool->add_vertex(m_a);\
	surface_tool->add_vertex(m_b);\
	surface_tool->add_vertex(m_b);\
	surface_tool->add_vertex(m_c);\
	surface_tool->add_vertex(m_c);\
	surface_tool->add_vertex(m_d);\
	surface_tool->add_vertex(m_d);\
	surface_tool->add_vertex(m_a);\
}

        float hsize=size*0.5;
        Vector3 right(hsize,0,0);
        Vector3 up(0,hsize,0);
        Vector3 back(0,0,-1.0);
        Vector3 front(0,0,0);

        ADD_QUAD( -up-right,-up+right,up+right,up-right);
        ADD_QUAD( -up-right+back,-up+right+back,up+right+back,up-right+back);
        ADD_QUAD( up+right,up+right+back,up-right+back,up-right);
        ADD_QUAD( -up+right,-up+right+back,-up-right+back,-up-right);

        right.x*=0.25;
        Vector3 tup( 0, up.y*3/2,back.z );
        ADD_TRIANGLE( tup, right+up+back, -right+up+back );

    }
    break;

    }

    return surface_tool->commit();

}
static int block_allocator_allocate(void* ctx, ump_dd_mem * mem)
{
	block_allocator * allocator;
	u32 left;
	block_info * last_allocated = NULL;
	int i = 0;

	BUG_ON(!ctx);
	BUG_ON(!mem);

	allocator = (block_allocator*)ctx;
	left = mem->size_bytes;

	BUG_ON(!left);
	BUG_ON(!&allocator->mutex);

	mem->nr_blocks = ((left + UMP_BLOCK_SIZE - 1) & ~(UMP_BLOCK_SIZE - 1)) / UMP_BLOCK_SIZE;
	mem->block_array = (ump_dd_physical_block*)vmalloc(sizeof(ump_dd_physical_block) * mem->nr_blocks);
	if (NULL == mem->block_array)
	{
		MSG_ERR(("Failed to allocate block array\n"));
		return 0;
	}

	if (down_interruptible(&allocator->mutex))
	{
		MSG_ERR(("Could not get mutex to do block_allocate\n"));
		return 0;
	}

	mem->size_bytes = 0;

	while ((left > 0) && (allocator->first_free))
	{
		block_info * block;

		block = allocator->first_free;
		allocator->first_free = allocator->first_free->next;
		block->next = last_allocated;
		last_allocated = block;
		allocator->num_free--;

		mem->block_array[i].addr = get_phys(allocator, block);
		mem->block_array[i].size = UMP_BLOCK_SIZE;
		mem->size_bytes += UMP_BLOCK_SIZE;

		i++;

		if (left < UMP_BLOCK_SIZE) left = 0;
		else left -= UMP_BLOCK_SIZE;
	}

	if (left)
	{
		block_info * block;
		/* release all memory back to the pool */
		while (last_allocated)
		{
			block = last_allocated->next;
			last_allocated->next = allocator->first_free;
			allocator->first_free = last_allocated;
			last_allocated = block;
			allocator->num_free++;
		}

		vfree(mem->block_array);
		mem->backend_info = NULL;
		mem->block_array = NULL;

		DBG_MSG(4, ("Could not find a mem-block for the allocation.\n"));
		up(&allocator->mutex);

		return 0;
	}

	mem->backend_info = last_allocated;

	up(&allocator->mutex);
	mem->is_cached=0;

	return 1;
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glViewport(0, 0, g_winSz[0], g_winSz[1]);
//SwapBuffers( g_hDC );
//return;
    //
    // setup the block1 with base matrices
    //
    // g_transfBlock1.m4_Proj already done
    vec3 up(0,1,0);
    look_at(g_transfBlock1.m4_View, g_camera.curEyePos, g_camera.curFocusPos, up);
    //g_transfBlock1.m4_ViewIT = ...todo
    g_transfBlock1.m4_ViewProj = g_transfBlock1.m4_Proj * g_transfBlock1.m4_View;
    g_transfBlock1.eyePos = g_camera.curEyePos;
    // copy the block to OGL
    if(fx_transfBlock1)
    {
        void* p;
        fx_transfBlock1->mapBuffer(&p);
        memcpy(p, &g_transfBlock1, sizeof(transfBlock1));
        fx_transfBlock1->unmapBuffer();
    }
    //-----------------------------------------------------------------
    //
    // Render a basic floor
    //
    //glBeginQuery(GL_TIME_ELAPSED, timerQueries[tqOffset]);
#define U 1.0f
#define DU 0.1f
    struct Grid
    {
        Grid() {
            Elts = 0;
            for(float i=-U; i<=(U+DU); i+=DU)
            {
                vtx[Elts++] = vec3(-U, 0, i);
                vtx[Elts++] = vec3( U, 0, i);
                vtx[Elts++] = vec3(i, 0,-U);
                vtx[Elts++] = vec3(i, 0, U);
            }
            glGenBuffers(1, &vbo);
            glBindBuffer(GL_ARRAY_BUFFER, vbo);
            glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*(10*10+2), vtx[0].vec_array, GL_STATIC_DRAW);
            glBindBuffer(GL_ARRAY_BUFFER, 0);
        }
        int     Elts;
        GLuint  vbo;
        vec3    vtx[10*10+2];
    };
    static Grid sgrid;
    if(fx_TechFloor)
    {
        fx_pass = fx_TechFloor->getPass(0);
        fx_pass->execute();
    }
    glEnableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glDisableVertexAttribArray(4);
    glBindBuffer(GL_ARRAY_BUFFER, sgrid.vbo);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
    glDrawArrays(GL_LINES, 0, sgrid.Elts);
    glDisableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    if(fx_pass)
        fx_pass->unbindProgram();
    fx_pass = NULL;

    //glEndQuery(GL_TIME_ELAPSED);
    //
    // Mesh rendering
    //
    //glBeginQuery(GL_TIME_ELAPSED, timerQueries[tqOffset+1]);

    if(fx_Tech)
    {
        fx_pass = fx_Tech->getPass(0);
        fx_pass->execute();
    }
    //===========> Draw the generated mesh
    draw1();
    //====================================

    if(fx_pass)
        fx_pass->unbindProgram();

    fx_pass = NULL;

    //glEndQuery(GL_TIME_ELAPSED);

#ifdef NOGLUT
    SwapBuffers( g_hDC );
#else
    glutSwapBuffers();
#endif

    //
    // Timer Query results
    //
    //tqOffset = tqOffset ? 0 : 2; // alternate between 2 groups
    //if(tqStart) // special case of the first render
    //    tqStart = false;
    //else
    //{
    //    int available = 0;
    //    while (!available)
    //    {
    //        glGetQueryObjectiv(timerQueries[tqOffset+1], GL_QUERY_RESULT_AVAILABLE, &available);
    //    }
    //    GLuint64 timeElapsed;
    //    for (int i = 0; i < 2; i++)
    //    {
    //        // See how much time the rendering of object i took in nanoseconds.
    //        glGetQueryObjectui64v(timerQueries[tqOffset+i], GL_QUERY_RESULT, &timeElapsed);
    //    }
    //}
}
Beispiel #9
0
void crw_handle_channel_report(void)
{
	up(&crw_semaphore);
}
Beispiel #10
0
/*H:030
 * Let's jump straight to the the main loop which runs the Guest.
 * Remember, this is called by the Launcher reading /dev/lguest, and we keep
 * going around and around until something interesting happens.
 */
int run_guest(struct lg_cpu *cpu, unsigned long __user *user)
{
	/* We stop running once the Guest is dead. */
	while (!cpu->lg->dead) {
		unsigned int irq;
		bool more;

		/* First we run any hypercalls the Guest wants done. */
		if (cpu->hcall) {
			// printk("=== DUMPING REGISTERS HYPERCALL ===\n");
			// dump_cpu_regs(cpu);
			do_hypercalls(cpu);
		}

		/*
		 * It's possible the Guest did a NOTIFY hypercall to the
		 * Launcher.
		 */
		if (cpu->pending_notify) {
			/*
			 * Does it just needs to write to a registered
			 * eventfd (ie. the appropriate virtqueue thread)?
			 */
			if (!send_notify_to_eventfd(cpu)) {
				/* OK, we tell the main Launcher. */
				if (put_user(cpu->pending_notify, user))
					return -EFAULT;
				return sizeof(cpu->pending_notify);
			}
		}

		/*
		 * All long-lived kernel loops need to check with this horrible
		 * thing called the freezer.  If the Host is trying to suspend,
		 * it stops us.
		 */
		try_to_freeze();

		/* Check for signals */
		if (signal_pending(current))
			return -ERESTARTSYS;

		/*
		 * Check if there are any interrupts which can be delivered now:
		 * if so, this sets up the hander to be executed when we next
		 * run the Guest.
		 */
		irq = interrupt_pending(cpu, &more);
		if (irq < LGUEST_IRQS)
			try_deliver_interrupt(cpu, irq, more);

		/*
		 * Just make absolutely sure the Guest is still alive.  One of
		 * those hypercalls could have been fatal, for example.
		 */
		if (cpu->lg->dead)
			break;

		/**
		 * If the guest is suspended skip.
		 */
		// printk("Checking for suspend\n");
		if(cpu->suspended) {
			// Sleep
			down_interruptible(&cpu->suspend_lock);
			// Unlock the lock since we no longer need it
			up(&cpu->suspend_lock);
			// set_current_state(TASK_INTERRUPTIBLE);
			// cond_resched();
			// schedule();
			// printk("Suspended\n");
			// continue;
			// TODO: Attempt to fix clock skew and nmi here?
			init_clockdev(cpu);
		}

		/*
		 * If the Guest asked to be stopped, we sleep.  The Guest's
		 * clock timer will wake us.
		 */
		if (cpu->halted) {
			set_current_state(TASK_INTERRUPTIBLE);
			/*
			 * Just before we sleep, make sure no interrupt snuck in
			 * which we should be doing.
			 */
			if (interrupt_pending(cpu, &more) < LGUEST_IRQS)
				set_current_state(TASK_RUNNING);
			else 
				schedule();
			continue;
		}

		/*
		 * OK, now we're ready to jump into the Guest.  First we put up
		 * the "Do Not Disturb" sign:
		 */
		local_irq_disable();

		/* Actually run the Guest until something happens. */
		lguest_arch_run_guest(cpu);

		/* Now we're ready to be interrupted or moved to other CPUs */
		local_irq_enable();

		/* Now we deal with whatever happened to the Guest. */
		lguest_arch_handle_trap(cpu);
	}

	/* Special case: Guest is 'dead' but wants a reboot. */
	if (cpu->lg->dead == ERR_PTR(-ERESTART))
		return -ERESTART;

	/* The Guest is dead => "No such file or directory" */
	return -ENOENT;
}
Beispiel #11
0
bool Camera::initDefault()
{
    auto size = Director::getInstance()->getWinSize();
    //create default camera
    auto projection = Director::getInstance()->getProjection();
    switch (projection)
    {
        case Director::Projection::_2D:
        {
            initOrthographic(size.width, size.height, -1024, 1024);
            setPosition3D(Vec3(0.0f, 0.0f, 0.0f));
            setRotation3D(Vec3(0.f, 0.f, 0.f));
            break;
        }
        case Director::Projection::_3D:
        {
            float zeye = Director::getInstance()->getZEye();
            initPerspective(60, (GLfloat)size.width / size.height, 10, zeye + size.height / 2.0f);
            Vec3 eye(size.width/2, size.height/2.0f, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f);
            setPosition3D(eye);
            lookAt(center, up);
            break;
        }
        default:
            CCLOG("unrecognized projection");
            break;
    }
    return true;
}
Beispiel #12
0
static int mipi_dsi_off(struct platform_device *pdev)
{
	int ret = 0;
	struct msm_fb_data_type *mfd;
	struct msm_panel_info *pinfo;

	pr_debug("%s+:\n", __func__);

	mfd = platform_get_drvdata(pdev);
	pinfo = &mfd->panel_info;

	if (mdp_rev >= MDP_REV_41)
		mutex_lock(&mfd->dma->ov_mutex);
	else
		down(&mfd->dma->mutex);

	mdp4_overlay_dsi_state_set(ST_DSI_SUSPEND);


	if (mfd->panel_info.type == MIPI_CMD_PANEL) {
		mipi_dsi_prepare_clocks();
		mipi_dsi_ahb_ctrl(1);
		mipi_dsi_clk_enable();

		/* make sure dsi_cmd_mdp is idle */
		mipi_dsi_cmd_mdp_busy();
	}
	/*
	 * Desctiption: change to DSI_CMD_MODE since it needed to
	 * tx DCS dsiplay off comamnd to panel
	 */
	mipi_dsi_op_mode_config(DSI_CMD_MODE);

	if (mfd->panel_info.type == MIPI_CMD_PANEL) {
		if (pinfo->lcd.vsync_enable) {
			if (pinfo->lcd.hw_vsync_mode && vsync_gpio >= 0) {
				if (MDP_REV_303 != mdp_rev)
					gpio_free(vsync_gpio);
			}
			mipi_dsi_set_tear_off(mfd);
		}
	}

	ret = panel_next_off(pdev);

#ifdef CONFIG_MSM_BUS_SCALING
	mdp_bus_scale_update_request(0);
#endif

	spin_lock_bh(&dsi_clk_lock);
	mipi_dsi_clk_disable();

	/* disbale dsi engine */
	MIPI_OUTP(MIPI_DSI_BASE + 0x0000, 0);

	mipi_dsi_phy_ctrl(0);

	mipi_dsi_ahb_ctrl(0);
	spin_unlock_bh(&dsi_clk_lock);

	mipi_dsi_unprepare_clocks();
	if (mipi_dsi_pdata && mipi_dsi_pdata->dsi_power_save)
		mipi_dsi_pdata->dsi_power_save(0);

	if (mdp_rev >= MDP_REV_41)
		mutex_unlock(&mfd->dma->ov_mutex);
	else
		up(&mfd->dma->mutex);

	pr_debug("%s-:\n", __func__);

	return ret;
}
Beispiel #13
0
void CLightPanel::updateSelectedLightInfo(f32 delta)
{
	EditorScene* scene = EditorScene::getInstance();
	if (!scene)
		return;

	SLightNodeInfo* info = scene->GetSelectedLightNodeInfo();
	if (!info)
		return;

	const f32 MOVE_UNIT = 10.0f;
	const f32 SCALING_UNIT = 5.0f;

	ICameraNode* camera = scene->GetCamera();
	XMFLOAT3 look = camera->getLookVector();
	XMFLOAT3 up(0, 1.0f, 0);
	XMFLOAT3 right = camera->getRightVector();

	XMVECTOR look_v = XMVectorSet(look.x, 0, look.z, 0);
	look_v = XMVector4Normalize(look_v);

	XMStoreFloat3(&look, look_v);

	XMFLOAT3 movement(0, 0, 0);
	f32 scaling = 0;

	if (GetAsyncKeyState('W') & 0x8000)
	{
		movement = math::VectorMultiply(look, delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState('S') & 0x8000)
	{
		movement = math::VectorMultiply(look, -delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState('A') & 0x8000)
	{
		movement = math::VectorMultiply(right, -delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState('D') & 0x8000)
	{
		movement = math::VectorMultiply(right, delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState('R') & 0x8000)
	{
		movement = math::VectorMultiply(up, delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState('F') & 0x8000)
	{
		movement = math::VectorMultiply(up, -delta * MOVE_UNIT);
	}

	if (GetAsyncKeyState(VK_ADD) & 0x8000)
	{
		scaling = SCALING_UNIT * delta;
	}

	if (GetAsyncKeyState(VK_SUBTRACT) & 0x8000)
	{
		scaling = -SCALING_UNIT * delta;
	}

	info->Position = math::VectorAdd(info->Position, movement);
	info->Range += scaling;
	if (info->Range < 0.1f)
		info->Range = 0.1f;

	scene->UpdateLightNodeInfo(info);
	ShowNodeInfo(info->Id);
}
Beispiel #14
0
static void driver_release(struct kobject * kobj)
{
	struct device_driver * drv = to_driver(kobj);
	up(&drv->unload_sem);
}
int main(int argc, char const *argv[])
{
	int rval,i;
	char ser[10];
	rval = access("ser.txt",F_OK);	
	signal(SIGINT,getMessage);
	char *p;
	printf("My pid is %d\n",getpid());
	if(rval!=0)
	{
		perror("File read error");
		exit(1);
	}
	initialize();
	int server_pid = atoi(ser);
	int mypid = getpid();
	sprintf(ser,"%d",mypid);
	pid_t cpid = fork();
	if(cpid==0)
	{
		//child process to receive the messages
		mymsgbuf recmsg;
		int parent_pid = getppid();
		signal(SIGINT,SIG_IGN);
		signal(SIGUSR1,exitChild);
		int i,rv_bytes;
		down(semid,PID_ARRAY);
		for(i=0;i<100;i++)
		{
			if(pid[i]==-1)
			{
				pid[i]=parent_pid;
				break;
			}
		}
		up(semid,PID_ARRAY);
		//receive from msg queue
		while (1) 
		{
        	rv_bytes = msgrcv(msgqid, &recmsg, MSG_SIZE, parent_pid, 0);
        	if(rv_bytes==-1)
	        {
	            perror("Queue Connection error");
	            exit(1);
	        }
	        else
	        {
	        	printf("--- Received Message:\"%s\"\n",recmsg.data);
	        }
	    }
        exit(0);    
    }
    //parent process	
    

    while(1)
    {
    	if(strcmp(tmpMsg,".")!=0)
    	{
    		if(strcmp(tmpMsg,"bye")==0)
    		{
    			//the process wants to exit. I need to free up the values.
    			kill(cpid,SIGUSR1);//send the signal to child to exit.
    			rval = 0;
    			down(semid,PID_ARRAY);	
    			for(i=0;i<100;i++)
    			{
    				if(pid[i]!=-1)
    				{
    					if(pid[i]==mypid)
    					{
    						pid[i]=-1;
    					}
    					else
    					{
    						rval++;
    					}
    				}
    			}
    			up(semid,PID_ARRAY);
    			if(rval==0)
    			{
    				//none of the children are present
    				p = getlogin();
    				waitOnSemop(semid,MSG_SEM);
    				strcpy(msg,p);
					strcat(msg,"/");
					strcat(msg,ser);
					strcat(msg,": ");
    				strcat(msg,"*");
    				down(semid,MSG_SEM);
    				strcpy(tmpMsg,".");
    				printf("--- All are gone. Have a nice day\n");
    				exit(0);
    				//send this message
    			}
    			else
    			{
    				printf("--- I am going. Have a nice chat\n");
    				exit(0);
    			}
    		}
    		else
    		{
    			p = getlogin();
    			waitOnSemop(semid,MSG_SEM);
    			strcpy(msg,p);
    			strcat(msg,"/");
    			strcat(msg,ser);
    			strcat(msg,": ");
    			strcat(msg,tmpMsg);
    			down(semid,MSG_SEM);
    			strcpy(tmpMsg,".");
    		}
    	}
    	else
    	{
    		p = getlogin();
			waitOnSemop(semid,MSG_SEM);
			if(strcmp(tmpMsg,".")==0)
			{
				strcpy(msg,p);
				strcat(msg,"/");
				strcat(msg,ser);
				strcat(msg,": ");
				strcat(msg,tmpMsg);
			}
			down(semid,MSG_SEM);
    	}

    }
	return 0;
}
Beispiel #16
0
static void flashLED(int led, int ms) {
	if (!led_state[led].led_task || ms < 1)
		return;
	led_state[led].period = ms;
	up(&led_state[led].led_sem);
}
Beispiel #17
0
//----------------------------------------------------------------------------------------------------------------------
void NGLScene::initializeGL()
{
#ifndef DARWIN
    glewExperimental = GL_TRUE;
    GLenum error = glewInit();
    if(error != GLEW_OK){
        std::cerr<<"GLEW IS NOT OK!!! "<<std::endl;
    }
#endif

  glClearColor(1.f, 1.f, 1.0f, 1.0f);			   // White Background
  //glClearColor(.7f, .7f, .7f, 1.0f);
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);

  // Now we will create a basic Camera from the graphics library
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  glm::vec3 from(0,0,5);
  glm::vec3 to(0,0,0);
  glm::vec3 up(0,1,0);
  // now load to our new camera
  m_cam = Camera(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_cam.setShape(45.0f,720.0f,576.0f,0.05f,350.0f);

  // Create our phong shader program
  m_phongShader = new ShaderProgram();
  // now we are going to create our shaders from source
  Shader vert("shaders/PhongVertex.glsl",GL_VERTEX_SHADER);
  Shader frag("shaders/PhongFragment.glsl",GL_FRAGMENT_SHADER);
  // attach the shaders to program
  m_phongShader->attachShader(&vert);
  m_phongShader->attachShader(&frag);
  m_phongShader->bindFragDataLocation(0, "fragColour");
  // now we have associated that data we can link the shader
  m_phongShader->link();
  // and make it active ready to
  m_phongShader->use();

  //Set some uniforms for our shader
  glUniform3f(m_phongShader->getUniformLoc("viewerPos"),from.x,from.y,from.z);
  glUniform3f(m_phongShader->getUniformLoc("material.ambient"),0.274725f,0.1995f,0.0745f);
  glUniform3f(m_phongShader->getUniformLoc("material.diffuse"),0.75164f,0.60648f,0.22648f);
  glUniform3f(m_phongShader->getUniformLoc("material.specular"),0.628281f,0.555802f,0.3666065f);
  glUniform1f(m_phongShader->getUniformLoc("material.shininess"),51.2f);

  glUniform4f(m_phongShader->getUniformLoc("light.position"),0.f,5.f,0.f,1.f);
  glUniform4f(m_phongShader->getUniformLoc("light.diffuse"),1.f,1.f,1.f,1.f);
  glUniform4f(m_phongShader->getUniformLoc("light.ambient"),1.f,1.f,1.f,1.f);
  glUniform4f(m_phongShader->getUniformLoc("light.specular"),1.f,1.f,1.f,1.f);
  glUniform1f(m_phongShader->getUniformLoc("light.constantAttenuation"),1.f);
  glUniform1f(m_phongShader->getUniformLoc("light.quadraticAttenuation"),0.f);
  glUniform1f(m_phongShader->getUniformLoc("light.linearAttenuation"),0.f);
  glUniform1f(m_phongShader->getUniformLoc("light.spotCosCutoff"),180.f);


  //Create our text drawer
  m_text = new Text(QFont("Ariel"));
  m_text->setScreenSize(width(),height());
  m_text->setColour(1.f,0.f,0.f);


  //Create our nice efficient particle drawer
  m_particleDrawer = new ParticleDrawer;
  m_particleDrawer->setParticleSize(0.025f);
  m_particleDrawer->setScreenWidth(width());

  //Create our SPH Solver
  m_SPHSolverCUDA = new SPHSolverCUDA;

  m_SPHSolverCUDA->genRandomSamples(160000);

  // Start our timer event. This will begin calling the TimerEvent function that updates our simulation.
  startTimer(0);
}
Beispiel #18
0
static int AOTOMdev_ioctl(struct inode *Inode, struct file *File, unsigned int cmd, unsigned long arg)
{
	int icon_nr = 0;
	static int mode = 0;
	int res = -EINVAL;
	dprintk(5, "%s > 0x%.8x\n", __func__, cmd);

	if(down_interruptible (&write_sem))
		return -ERESTARTSYS;

	switch(cmd) {
	case VFDSETMODE:
	case VFDSETLED:
	case VFDICONDISPLAYONOFF:
	case VFDSETTIME:
	case VFDBRIGHTNESS:
		if (copy_from_user(&aotom_data, (void *) arg, sizeof(aotom_data)))
			return -EFAULT;
	}

	switch(cmd) {
	case VFDSETMODE:
		mode = aotom_data.u.mode.compat;
		break;
	case VFDSETLED:
#if defined(SPARK) || defined(SPARK7162)
		if (aotom_data.u.led.led_nr > -1 && aotom_data.u.led.led_nr < LED_MAX) {
			switch (aotom_data.u.led.on) {
			case LOG_OFF:
			case LOG_ON:
				res = YWPANEL_VFD_SetLed(aotom_data.u.led.led_nr, aotom_data.u.led.on);
				led_state[aotom_data.u.led.led_nr].state = aotom_data.u.led.on;
				break;
			default: // toggle (for aotom_data.u.led.on * 10) ms
				flashLED(aotom_data.u.led.led_nr, aotom_data.u.led.on * 10);
			}
		}
#endif
		break;
	case VFDBRIGHTNESS:
		if (aotom_data.u.brightness.level < 0)
			aotom_data.u.brightness.level = 0;
		else if (aotom_data.u.brightness.level > 7)
			aotom_data.u.brightness.level = 7;
		res = YWPANEL_VFD_SetBrightness(aotom_data.u.brightness.level);
		break;
	case VFDICONDISPLAYONOFF:
	{
#if defined(SPARK)
		switch (aotom_data.u.icon.icon_nr) {
		case 0:
			res = YWPANEL_VFD_SetLed(LED_RED, aotom_data.u.icon.on);
			led_state[LED_RED].state = aotom_data.u.icon.on;
			break;
		case 35:
			res = YWPANEL_VFD_SetLed(LED_GREEN, aotom_data.u.icon.on);
			led_state[LED_GREEN].state = aotom_data.u.icon.on;
			break;
		default:
			break;
		}
#endif
#if defined(SPARK7162)
		icon_nr = aotom_data.u.icon.icon_nr;
		//e2 icons workarround
		//printk("icon_nr = %d\n", icon_nr);
		if (icon_nr >= 256) {
			icon_nr = icon_nr / 256;
			switch (icon_nr) {
			case 0x11:
				icon_nr = 0x0E; //widescreen
				break;
			case 0x13:
				icon_nr = 0x0B; //CA
				break;
			case 0x15:
				icon_nr = 0x19; //mp3
				break;
			case 0x17:
				icon_nr = 0x1A; //ac3
				break;
			case 0x1A:
				icon_nr = 0x03; //play
				break;
			case 0x1e:
				icon_nr = 0x07; //record
				break;
			case 38:
				break; //cd part1
			case 39:
				break; //cd part2
			case 40:
				break; //cd part3
			case 41:
				break; //cd part4
			default:
				icon_nr = 0; //no additional symbols at the moment
				break;
			}
		}	  
		if (aotom_data.u.icon.on != 0)
			aotom_data.u.icon.on = 1;
		if (icon_nr > 0 && icon_nr <= 45 )
			res = aotomSetIcon(icon_nr, aotom_data.u.icon.on);
		if (icon_nr == 46){
			switch (aotom_data.u.icon.on){
			case 1:
				VFD_set_all_icons();
				res = 0;
				break;
			case 0:
				VFD_clear_all_icons();
				res = 0;
				break;
			default:
				break;
			}
		}
#endif		
		mode = 0;
		break;
	}
	case VFDSTANDBY:
	{
#if defined(SPARK) || defined(SPARK7162)
		u32 uTime = 0;
		//u32 uStandByKey = 0;
		//u32 uPowerOnTime = 0;
		get_user(uTime, (int *) arg);
		//printk("uTime = %d\n", uTime);

		//uPowerOnTime = YWPANEL_FP_GetPowerOnTime();
		//printk("1uPowerOnTime = %d\n", uPowerOnTime);

		YWPANEL_FP_SetPowerOnTime(uTime);

		//uPowerOnTime = YWPANEL_FP_GetPowerOnTime();
		//printk("2uPowerOnTime = %d\n", uPowerOnTime);
		#if 0
		uStandByKey = YWPANEL_FP_GetStandByKey(0);
		printk("uStandByKey = %d\n", uStandByKey);
		uStandByKey = YWPANEL_FP_GetStandByKey(1);
		printk("uStandByKey = %d\n", uStandByKey);
		uStandByKey = YWPANEL_FP_GetStandByKey(2);
		printk("uStandByKey = %d\n", uStandByKey);
		uStandByKey = YWPANEL_FP_GetStandByKey(3);
		printk("uStandByKey = %d\n", uStandByKey);
		uStandByKey = YWPANEL_FP_GetStandByKey(4);
		printk("uStandByKey = %d\n", uStandByKey);
		#endif
		clear_display();
		YWPANEL_FP_ControlTimer(true);
		YWPANEL_FP_SetCpuStatus(YWPANEL_CPUSTATE_STANDBY);
		res = 0;
#endif
		break;
	}
	case VFDSETTIME2:
	{
		u32 uTime = 0;
		res = get_user(uTime, (int *)arg);
		if (! res)
		{
			res = YWPANEL_FP_SetTime(uTime);
			YWPANEL_FP_ControlTimer(true);
		}
		break;
	}
	case VFDSETTIME:
		res = aotomSetTime(aotom_data.u.time.time);
		break;
	case VFDGETTIME:
	{
#if defined(SPARK) || defined(SPARK7162)
		u32 uTime = 0;
		uTime = YWPANEL_FP_GetTime();
		//printk("uTime = %d\n", uTime);
		res = put_user(uTime, (int *) arg);
#endif
		break;
	}
	case VFDGETWAKEUPMODE:
		break;
	case VFDDISPLAYCHARS:
		if (mode == 0)
		{
			if (copy_from_user(&vfd_data, (void *) arg, sizeof(vfd_data)))
				return -EFAULT;
			if (vfd_data.length > sizeof(vfd_data.data))
				vfd_data.length = sizeof(vfd_data.data);
			while ((vfd_data.length > 0) && (vfd_data.data[vfd_data.length - 1 ] == '\n'))
				vfd_data.length--;
				res = run_draw_thread(&vfd_data);
		} else
			mode = 0;
		break;
	case VFDDISPLAYWRITEONOFF:
		break;
	case VFDDISPLAYCLR:
		vfd_data.length = 0;
		res = run_draw_thread(&vfd_data);
		break;
#if defined(SPARK)
	case 0x5305:
		res = 0;
		break;
#endif
	case 0x5401:
		res = 0;
		break;
	case VFDGETSTARTUPSTATE:
	{
		YWPANEL_STARTUPSTATE_t State;
		if (YWPANEL_FP_GetStartUpState(&State))
			res = put_user(State, (int *) arg);
		break;
	}
	case VFDGETVERSION:
	{
		YWPANEL_Version_t panel_version;
		memset(&panel_version, 0, sizeof(YWPANEL_Version_t));
		if (YWPANEL_FP_GetVersion(&panel_version))
			res = put_user (panel_version.DisplayInfo, (int *)arg);
		break;
	}

	default:
		printk("VFD/AOTOM: unknown IOCTL 0x%x\n", cmd);
		mode = 0;
		break;
	}

	up(&write_sem);

	dprintk(5, "%s <\n", __func__);
	return res;
}
Beispiel #19
0
//-.-.-.-.-.-.-.-.-.-.-.-.-.-.- Dtu2xxRequestExclusiveAccess -.-.-.-.-.-.-.-.-.-.-.-.-.-.-
//
// Called by DeviceIoControl to request exclusive access to an Rx channel.
// If exclusive access is granted, the thread pointer is stored, so that the exclusive-
// access lock can be released upon a CLOSE of the thread.
// The exclusive-access variables are protected by a spin lock.
//
Int  Dtu2xxRequestExclusiveAccess(
	IN PDTU2XX_FDO  pFdo,			// Functional device object
	IN struct file* pFileObject,	// File object requesting/dropping excl. access
	IN Int  PortIndex,				// Channel index
	IN Int  Request,				// 0 = Request exclusive access
									// 1 = Release exclusive access
	OUT Int*  pGranted)				// Granted Yes / No
{
	Channel* pCh=NULL;

	// Check port index
	if ( PortIndex<0 || PortIndex >= pFdo->m_NumChannels )
	{
		DTU2XX_LOG( KERN_INFO, "Dtu2xxRequestExclusiveAccess: PortIndex=%d INVALID",
					PortIndex );
		return -EFAULT;
	}
	pCh = &pFdo->m_Channel[PortIndex];

#if LOG_LEVEL > 0
	DTU2XX_LOG( KERN_INFO, "[%d] Dtu2xxRequestExclusiveAccess: Request=%d",
			    PortIndex, Request );
#endif

	if (Request!=0 && Request!=1)
	{
		DTU2XX_LOG( KERN_INFO, "[%d] Dtu2xxRequestExclusiveAccess: Request=%d ILLEGAL",
				    PortIndex, Request );
		return -EFAULT;
	}

	if ( 0!=down_interruptible(&pCh->m_ExclAccLock) )
		return -EFAULT;

	if (Request == 0)
	{
		// Request exclusive access
		if (pCh->m_ExclAccess == 0)
		{
			pCh->m_ExclAccess = 1;
			pCh->m_pExclAccFileObject = pFileObject;
			*pGranted = 1;
#if LOG_LEVEL > 0
			DTU2XX_LOG( KERN_INFO, "[%d] Dtu2xxRequestExclusiveAccess: Exclusive access "
					    "GRANTED", PortIndex );
#endif
		} else {
			*pGranted = 0;
#if LOG_LEVEL > 0
			DTU2XX_LOG( KERN_INFO, "[%d] Dtu2xxRequestExclusiveAccess: Exclusive access "
					    "DENIED", PortIndex );
#endif
		}
	}
	else
	{
		// Release exclusive access.
		// Based on cooperative model: The exclusive-access lock is ALWAYS cleared,
		// without file-object check.
		// So, DeviceIoControl can also be used to unconditionally clear the lock.
		pCh->m_ExclAccess = 0;
#if LOG_LEVEL > 0
		DTU2XX_LOG( KERN_INFO, "[%d] Dtu2xxRequestExclusiveAccess: Exclusive access "
				    "RELEASED", PortIndex );
#endif
	}
	up(&pCh->m_ExclAccLock);
	return 0;
}
Beispiel #20
0
ThreeWaySqueezeDemo::ThreeWaySqueezeDemo(hkDemoEnvironment* env):	hkDefaultPhysicsDemo(env)
{
	// Disable warning
	hkError::getInstance().setEnabled(0xf0de4356, false);	// 'Your m_contactRestingVelocity seems to be too small'

	//
	// Setup the camera
	//
	{
		hkVector4 from(0.0f, 10.0f, 10.0f);
		hkVector4 to  (0.0f,  0.0f,  0.0f);
		hkVector4 up  (0.0f,  1.0f,  0.0f);
		setupDefaultCameras( env, from, to, up );
	}

	//
	// Create the world
	//
	{
		hkpWorldCinfo info;
		info.setupSolverInfo( hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM );
		info.setBroadPhaseWorldSize( 350.0f );  
		info.m_gravity.set(0,-40,0);
		info.m_collisionTolerance = 0.1f;
		info.m_numToisTillAllowedPenetrationToi = 1.1f;

		m_world = new hkpWorld( info );
		m_world->lock();

		hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher());
		setupGraphics();
	}

	{
		hkpCollisionFilter* cf = new My3WCollisionFilter();
		m_world->setCollisionFilter(cf);
		cf->removeReference();
	}

	// Build a Base
	hkVector4 baseSize( 50.0f, 1.0f, 50.0f);
	{ 
		hkpRigidBodyCinfo rci;
		rci.m_shape = new hkpBoxShape( baseSize );
		rci.m_position.set(0.0f, -0.5f, 0.0f);
		rci.m_motionType = hkpMotion::MOTION_FIXED;
			
		// Create a rigid body (using the template above).
		hkpRigidBody* base = new hkpRigidBody(rci);

		// Remove reference since the body now "owns" the Shape.
		rci.m_shape->removeReference();

		// Finally add body so we can see it, and remove reference since the world now "owns" it.
		m_world->addEntity( base )->removeReference();
	} 
	
	
	// Create a circle of keyframed objects 
	// Each of the objects is given a different increasing priority
	// We set the priority as a property on the object and extract this i nthe callback.
	hkVector4 blockerSize(1,3,5);
	hkpShape* blocker = new hkpBoxShape( blockerSize );
	{
		//hkPseudoRandomGenerator ran(100);
		for (int b = 0; b < NUM_OBJECTS; b++ )
		{
			hkVector4 up(0,1,0);
			hkReal angle = hkReal(b) / NUM_OBJECTS * HK_REAL_PI * 2;

			hkpRigidBodyCinfo rci;
			rci.m_position.set(5,0,0);
			rci.m_rotation.setAxisAngle( up, angle );
			rci.m_position.setRotatedDir( rci.m_rotation, rci.m_position );
			rci.m_shape = blocker;
			
			// If we set this to true, the body is fixed, and no mass properties need to be computed.
			rci.m_motionType = hkpMotion::MOTION_KEYFRAMED;
			if (b < 1)
			{
				rci.m_qualityType = HK_COLLIDABLE_QUALITY_KEYFRAMED;
			}
			else
			{
				rci.m_qualityType = HK_COLLIDABLE_QUALITY_FIXED;
			}

			m_objects[b] = new hkpRigidBody( rci );
			m_world->addEntity( m_objects[b] );
			m_objects[b]->removeReference();

			int color = rci.m_qualityType == HK_COLLIDABLE_QUALITY_FIXED ?
						hkColor::rgbFromFloats(1.0f, 0.0f, 0.0f, 1.0f) :
						hkColor::rgbFromFloats(0.0f, 1.0f, 0.0f, 1.0f) ;

			HK_SET_OBJECT_COLOR((hkUlong)m_objects[b]->getCollidable(), color );
		}
	}
	blocker->removeReference();

	//
	// Crate middle sphere
	//

	{
		hkpShape* shape = new hkpSphereShape(1.5f);
		hkpRigidBodyCinfo rbInfo;
		rbInfo.m_shape = shape;
		rbInfo.m_qualityType = HK_COLLIDABLE_QUALITY_CRITICAL;
		hkpRigidBody* body = new hkpRigidBody(rbInfo);
		m_world->addEntity(body);
		body->removeReference();
		shape->removeReference();
	}
	
	m_prevObj = 0;

	// Zero current time at start
	m_currentTime = 0.0f;

	m_world->unlock();
}
void uartfile_starttx(struct console * con)
{
	up(&recv_tsk_sem);
}
static int jffs2_prepare_write (struct file *filp, struct page *pg,
				unsigned start, unsigned end)
{
	struct inode *inode = pg->mapping->host;
	struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode);
	uint32_t pageofs = pg->index << PAGE_CACHE_SHIFT;
	int ret = 0;

	D1(printk(KERN_DEBUG "jffs2_prepare_write()\n"));

	if (pageofs > inode->i_size) {
		/* Make new hole frag from old EOF to new page */
		struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb);
		struct jffs2_raw_inode ri;
		struct jffs2_full_dnode *fn;
		uint32_t phys_ofs, alloc_len;

		D1(printk(KERN_DEBUG "Writing new hole frag 0x%x-0x%x between current EOF and new page\n",
			  (unsigned int)inode->i_size, pageofs));

		ret = jffs2_reserve_space(c, sizeof(ri), &phys_ofs, &alloc_len,
					ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE);
		if (ret)
			return ret;

		down(&f->sem);
		memset(&ri, 0, sizeof(ri));

		ri.magic = cpu_to_je16(JFFS2_MAGIC_BITMASK);
		ri.nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE);
		ri.totlen = cpu_to_je32(sizeof(ri));
		ri.hdr_crc = cpu_to_je32(crc32(0, &ri, sizeof(struct jffs2_unknown_node)-4));

		ri.ino = cpu_to_je32(f->inocache->ino);
		ri.version = cpu_to_je32(++f->highest_version);
		ri.mode = cpu_to_jemode(inode->i_mode);
		ri.uid = cpu_to_je16(inode->i_uid);
		ri.gid = cpu_to_je16(inode->i_gid);
		ri.isize = cpu_to_je32(max((uint32_t)inode->i_size, pageofs));
		ri.atime = ri.ctime = ri.mtime = cpu_to_je32(get_seconds());
		ri.offset = cpu_to_je32(inode->i_size);
		ri.dsize = cpu_to_je32(pageofs - inode->i_size);
		ri.csize = cpu_to_je32(0);
		ri.compr = JFFS2_COMPR_ZERO;
		ri.node_crc = cpu_to_je32(crc32(0, &ri, sizeof(ri)-8));
		ri.data_crc = cpu_to_je32(0);

		fn = jffs2_write_dnode(c, f, &ri, NULL, 0, phys_ofs, ALLOC_NORMAL);

		if (IS_ERR(fn)) {
			ret = PTR_ERR(fn);
			jffs2_complete_reservation(c);
			up(&f->sem);
			return ret;
		}
		ret = jffs2_add_full_dnode_to_inode(c, f, fn);
		if (f->metadata) {
			jffs2_mark_node_obsolete(c, f->metadata->raw);
			jffs2_free_full_dnode(f->metadata);
			f->metadata = NULL;
		}
		if (ret) {
			D1(printk(KERN_DEBUG "Eep. add_full_dnode_to_inode() failed in prepare_write, returned %d\n", ret));
			jffs2_mark_node_obsolete(c, fn->raw);
			jffs2_free_full_dnode(fn);
			jffs2_complete_reservation(c);
			up(&f->sem);
			return ret;
		}
		jffs2_complete_reservation(c);
		inode->i_size = pageofs;
		up(&f->sem);
	}

	/* Read in the page if it wasn't already present, unless it's a whole page */
	if (!PageUptodate(pg) && (start || end < PAGE_CACHE_SIZE)) {
		down(&f->sem);
		ret = jffs2_do_readpage_nolock(inode, pg);
		up(&f->sem);
	}
	D1(printk(KERN_DEBUG "end prepare_write(). pg->flags %lx\n", pg->flags));
	return ret;
}
Beispiel #23
0
static int wixevent_ioctl ( struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg ) {
	wixEventList *last, *el;
	wixEvent event;
	int	res;

	if ( !access_ok(VERIFY_WRITE, arg, sizeof(wixEvent)) )
		return -EFAULT;

	switch ( cmd ) {
		case WIX_EVENT_IOCTL_SND:
		case WIX_EVENT_IOCTL_RCV:
		case WIX_EVENT_IOCTL_PEEK:
			if ( copy_from_user(&event, (wixEvent *)arg, sizeof(wixEvent)) ) {
				return -EFAULT;
			}
			break;
	}

	last = el = NULL;

	switch ( cmd ) {
		/* Push event to the event queue */
		case WIX_EVENT_IOCTL_SND:

			res = wixevent_send( &event );
			if ( res != WIX_RC_OK ) {
				return res;
			}
			break;

		/* Pull for currently pending events */
		/* If event.type == 0, pull the first event */
		/* If event.type != 0, pull the specific event of that type */
		case WIX_EVENT_IOCTL_RCV:

			down( &wixevent_semaphore );
			if ( WixEventHead == NULL ) {
				up( &wixevent_semaphore );
				return -EPERM;
			}
			if ( event.type == 0 ) {
				if ( copy_to_user((wixEvent *)arg, (wixEvent *)&WixEventHead->event, sizeof(wixEvent)) ) {
					up( &wixevent_semaphore );
					return -EFAULT;
				}
				if ( WixEventHead != WixEventTail ) {
					el = WixEventHead;
					WixEventHead = WixEventHead->next;
					kfree(el);
				} else {
					el = WixEventHead;
					WixEventHead = WixEventTail = NULL;
					kfree( el );
				}
				--wixEventCount;
			} else {
				el = WixEventHead;
				while ( event.type != el->event.type ) {
					last = el;
					el = el->next;
					if ( el == NULL ) {
						up( &wixevent_semaphore );
						return -EPERM;
					}
				}
				if ( el == WixEventHead ) {
					if ( WixEventHead != WixEventTail ) {
						WixEventHead = WixEventHead->next;
					} else {
						WixEventHead = WixEventTail = NULL;
					}
				} else if ( el == WixEventTail ) {
					WixEventTail = last;
					WixEventTail->next = NULL;
				} else {
					last->next = el->next;
				}
				if ( copy_to_user((wixEvent *)arg, (wixEvent *)&el->event, sizeof(wixEvent)) ) {
					up( &wixevent_semaphore );
					return -EFAULT;
				}
				kfree( el );
				--wixEventCount;
			}
			up( &wixevent_semaphore );
			break;

		/* Peek the event queue */
		/* If event.type == 0, peek the first event */
		/* If event.type != 0, peek the specific event of that type */
		/* Use event.value to peek the Nth event from the event queue */
		case WIX_EVENT_IOCTL_PEEK:

			down( &wixevent_semaphore );
			if ( WixEventHead == NULL ) {
				up( &wixevent_semaphore );
				return -EPERM;
			}
			if ( event.type == 0 ) {
				el = WixEventHead;
				while ( event.value > 1 ) {
					el = el->next;
					if ( el == NULL ) {
						up( &wixevent_semaphore );
						return -EPERM;
					}
					--event.value;
				}
				if ( copy_to_user((wixEvent *)arg, (wixEvent *)&el->event, sizeof(wixEvent)) ) {
					up( &wixevent_semaphore );
					return -EFAULT;
				}
			} else {
				el = WixEventHead;
				while ( (event.type!=el->event.type) || (event.value>1) ) {
					if ( event.type == el->event.type )
						--event.value;
					el = el->next;
					if ( el == NULL ) {
						up( &wixevent_semaphore );
						return -EPERM;
					}
				}
				if ( copy_to_user((wixEvent *)arg, (wixEvent *)&el->event, sizeof(wixEvent)) ) {
					up( &wixevent_semaphore );
					return -EFAULT;
				}
			}
			up( &wixevent_semaphore );
			break;

		case WIX_EVENT_IOCTL_COUNT:

			down( &wixevent_semaphore );
			if ( copy_to_user((int *)arg, (int *)&wixEventCount, sizeof(int)) ) {
				up( &wixevent_semaphore );
				return -EFAULT;
			}
			up( &wixevent_semaphore );
			break;

		default:
			return WIX_RC_ERR;
	}

	return WIX_RC_OK;
}
bool KX_TrackToActuator::Update(double curtime, bool frame)
{
	bool result = false;
	bool bNegativeEvent = IsNegativeEvent();
	RemoveAllEvents();

	if (bNegativeEvent)
	{
		// do nothing on negative events
	}
	else if (m_object)
	{
		KX_GameObject* curobj = (KX_GameObject*) GetParent();
		MT_Vector3 dir = ((KX_GameObject*)m_object)->NodeGetWorldPosition() - curobj->NodeGetWorldPosition();
		if (dir.length2())
			dir.normalize();
		MT_Vector3 up(0,0,1);
		
		
#ifdef DSADSA
		switch (m_upflag)
		{
		case 0:
			{
				up.setValue(1.0,0,0);
				break;
			} 
		case 1:
			{
				up.setValue(0,1.0,0);
				break;
			}
		case 2:
		default:
			{
				up.setValue(0,0,1.0);
			}
		}
#endif 
		if (m_allow3D)
		{
			up = (up - up.dot(dir) * dir).safe_normalized();
			
		}
		else
		{
			dir = (dir - up.dot(dir)*up).safe_normalized();
		}
		
		MT_Vector3 left;
		MT_Matrix3x3 mat;
		
		switch (m_trackflag)
		{
		case 0: // TRACK X
			{
				// (1.0 , 0.0 , 0.0 ) x direction is forward, z (0.0 , 0.0 , 1.0 ) up
				left  = dir.safe_normalized();
				dir = (left.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
				
				break;
			};
		case 1:	// TRACK Y
			{
				// (0.0 , 1.0 , 0.0 ) y direction is forward, z (0.0 , 0.0 , 1.0 ) up
				left  = (dir.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
				
				break;
			}
			
		case 2: // track Z
			{
				left = up.safe_normalized();
				up = dir.safe_normalized();
				dir = left;
				left  = (dir.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
				break;
			}
			
		case 3: // TRACK -X
			{
				// (1.0 , 0.0 , 0.0 ) x direction is forward, z (0.0 , 0.0 , 1.0 ) up
				left  = -dir.safe_normalized();
				dir = -(left.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
				
				break;
			};
		case 4: // TRACK -Y
			{
				// (0.0 , -1.0 , 0.0 ) -y direction is forward, z (0.0 , 0.0 , 1.0 ) up
				left  = (-dir.cross(up)).safe_normalized();
				mat.setValue (
					left[0], -dir[0],up[0], 
					left[1], -dir[1],up[1],
					left[2], -dir[2],up[2]
					);
				break;
			}
		case 5: // track -Z
			{
				left = up.safe_normalized();
				up = -dir.safe_normalized();
				dir = left;
				left  = (dir.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
				
				break;
			}
			
		default:
			{
				// (1.0 , 0.0 , 0.0 ) -x direction is forward, z (0.0 , 0.0 , 1.0 ) up
				left  = -dir.safe_normalized();
				dir = -(left.cross(up)).safe_normalized();
				mat.setValue (
					left[0], dir[0],up[0], 
					left[1], dir[1],up[1],
					left[2], dir[2],up[2]
					);
			}
		}
		
		MT_Matrix3x3 oldmat;
		oldmat= curobj->NodeGetWorldOrientation();
		
		/* erwin should rewrite this! */
		mat= matrix3x3_interpol(oldmat, mat, m_time);
		

		if (m_parentobj) { // check if the model is parented and calculate the child transform
				
			MT_Point3 localpos;
			localpos = curobj->GetSGNode()->GetLocalPosition();
			// Get the inverse of the parent matrix
			MT_Matrix3x3 parentmatinv;
			parentmatinv = m_parentobj->NodeGetWorldOrientation ().inverse ();
			// transform the local coordinate system into the parents system
			mat = parentmatinv * mat;
			// append the initial parent local rotation matrix
			mat = m_parentlocalmat * mat;

			// set the models tranformation properties
			curobj->NodeSetLocalOrientation(mat);
			curobj->NodeSetLocalPosition(localpos);
			//curobj->UpdateTransform();
		}
		else
		{
			curobj->NodeSetLocalOrientation(mat);
		}

		result = true;
	}

	return result;
}
Beispiel #25
0
ssize_t cifs_getxattr(struct dentry * direntry, const char * ea_name,
         void * ea_value, size_t buf_size)
{
	ssize_t rc = -EOPNOTSUPP;
#ifdef CONFIG_CIFS_XATTR
	int xid;
	struct cifs_sb_info *cifs_sb;
	struct cifsTconInfo *pTcon;
	struct super_block * sb;
	char * full_path;

	if(direntry == NULL)
		return -EIO;
	if(direntry->d_inode == NULL)
		return -EIO;
	sb = direntry->d_inode->i_sb;
	if(sb == NULL)
		return -EIO;

	xid = GetXid();

	cifs_sb = CIFS_SB(sb);
	pTcon = cifs_sb->tcon;

	down(&sb->s_vfs_rename_sem);
	full_path = build_path_from_dentry(direntry);
	up(&sb->s_vfs_rename_sem);
	if(full_path == NULL) {
		FreeXid(xid);
		return -ENOMEM;
	}
	/* return dos attributes as pseudo xattr */
	/* return alt name if available as pseudo attr */
	if(ea_name == NULL) {
		cFYI(1,("Null xattr names not supported"));
	} else if(strncmp(ea_name,CIFS_XATTR_USER_PREFIX,5) == 0) {
		if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
			goto get_ea_exit;

		if(strncmp(ea_name,CIFS_XATTR_DOS_ATTRIB,14) == 0) {
			cFYI(1,("attempt to query cifs inode metadata"));
			/* revalidate/getattr then populate from inode */
		} /* BB add else when above is implemented */
		ea_name += 5; /* skip past user. prefix */
		rc = CIFSSMBQueryEA(xid,pTcon,full_path,ea_name,ea_value,
			buf_size, cifs_sb->local_nls);
	} else if(strncmp(ea_name, CIFS_XATTR_OS2_PREFIX,4) == 0) {
		if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
			goto get_ea_exit;

		ea_name += 4; /* skip past os2. prefix */
		rc = CIFSSMBQueryEA(xid,pTcon,full_path,ea_name,ea_value,
			buf_size, cifs_sb->local_nls);
	} else if(strncmp(ea_name,POSIX_ACL_XATTR_ACCESS,strlen(POSIX_ACL_XATTR_ACCESS)) == 0) {
#ifdef CONFIG_CIFS_POSIX
		rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
				ea_value, buf_size, ACL_TYPE_ACCESS, 
				cifs_sb->local_nls);
#else 
		cFYI(1,("query POSIX ACL not supported yet"));
#endif /* CONFIG_CIFS_POSIX */
	} else if(strncmp(ea_name,POSIX_ACL_XATTR_DEFAULT,strlen(POSIX_ACL_XATTR_DEFAULT)) == 0) {
#ifdef CONFIG_CIFS_POSIX
		rc = CIFSSMBGetPosixACL(xid, pTcon, full_path,
				ea_value, buf_size, ACL_TYPE_DEFAULT, 
				cifs_sb->local_nls);
#else 
		cFYI(1,("query POSIX default ACL not supported yet"));
#endif
	} else if(strncmp(ea_name,
		  CIFS_XATTR_TRUSTED_PREFIX,XATTR_TRUSTED_PREFIX_LEN) == 0) {
		cFYI(1,("Trusted xattr namespace not supported yet"));
	} else if(strncmp(ea_name,
		  CIFS_XATTR_SECURITY_PREFIX,XATTR_SECURITY_PREFIX_LEN) == 0) {
		cFYI(1,("Security xattr namespace not supported yet"));
	} else {
		cFYI(1,("illegal xattr name request %s (only user namespace supported)",ea_name));
	}

	/* We could add an additional check for streams ie 
	    if proc/fs/cifs/streamstoxattr is set then
		search server for EAs or streams to 
		returns as xattrs */

	if(rc == -EINVAL)
		rc = -EOPNOTSUPP; 

get_ea_exit:
	if (full_path)
		kfree(full_path);
	FreeXid(xid);
#endif
	return rc;
}
Beispiel #26
0
int main(int argc, char* argv[])
{
	// Build your scene and setup your camera here, by calling
	// functions from Raytracer.  The code here sets up an example
	// scene and renders it from two different view points, DO NOT
	// change this if you're just implementing part one of the
	// assignment.
	Raytracer raytracer;
	int width = 320;
	int height = 240;

	if (argc == 3) {
		width = atoi(argv[1]);
		height = atoi(argv[2]);
	}

	if (argc == 4) {
		width = atoi(argv[1]);
		height = atoi(argv[2]);
		antiAliasing = atoi(argv[3]);
	}

	// Camera parameters.
	Point3D eye(0, 0, 1);
	Vector3D view(0, 0, -1);
	Vector3D up(0, 1, 0);
	double fov = 60;

	// Defines a material for shading.
	Material gold( Colour(0.3, 0.3, 0.3), Colour(0.75164, 0.60648, 0.22648),
			Colour(0.628281, 0.555802, 0.366065),
			51.2 );
	Material jade( Colour(0, 0, 0), Colour(0.54, 0.89, 0.63),
			Colour(0.316228, 0.316228, 0.316228),
			12.8 );

	// Defines a point light source.
	raytracer.addLightSource( new PointLight(Point3D(0, 0, 5),
				Colour(0.9, 0.9, 0.9) ) );

	// Add a unit square into the scene with material mat.
	SceneDagNode* sphere = raytracer.addObject( new UnitSphere(), &gold );
	SceneDagNode* plane = raytracer.addObject( new UnitSquare(), &jade );

	// Apply some transformations to the unit square.
	double factor1[3] = { 1.0, 2.0, 1.0 };
	double factor2[3] = { 6.0, 6.0, 6.0 };
	raytracer.translate(sphere, Vector3D(0, 0, -5));
	raytracer.rotate(sphere, 'x', -45);
	raytracer.rotate(sphere, 'z', 45);
	raytracer.scale(sphere, Point3D(0, 0, 0), factor1);

	raytracer.translate(plane, Vector3D(0, 0, -7));
	raytracer.rotate(plane, 'z', 45);
	raytracer.scale(plane, Point3D(0, 0, 0), factor2);

	// Render the scene, feel free to make the image smaller for
	// testing purposes.
	raytracer.render(width, height, eye, view, up, fov, "view1.bmp");

	// Render it from a different point of view.
	Point3D eye2(4, 2, 1);
	Vector3D view2(-4, -2, -6);
	raytracer.render(width, height, eye2, view2, up, fov, "view2.bmp");

	return 0;
}
Beispiel #27
0
void GLWindow::initializeGL()
{
  // we need to initialise the NGL lib which will load all of the OpenGL functions, this must
  // be done once we have a valid GL context but before we call any GL commands. If we dont do
  // this everything will crash
  ngl::NGLInit::instance();
  glClearColor(0.4f, 0.4f, 0.4f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
  // as re-size is not explicitly called we need to do this.
  glViewport(0,0,width(),height());

  // Now we will create a basic Camera from the graphics library
  // This is a static camera so it only needs to be set once
  // First create Values for the camera position
  ngl::Vec3 from(60, 10, 305);
  ngl::Vec3 to(60, 5, -5);
  ngl::Vec3 up(0,1,0);
  // now load to our new camera
  m_cam= new ngl::Camera(from,to,up);

  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  m_cam->setShape(45,(float)720.0/576.0,0.05,350);

  // now load the default nglColour shader and set the colour for it.
  ngl::ShaderLib *shader = ngl::ShaderLib::instance();

  // load a frag and vert shaders

  shader->createShaderProgram("PhongShader");

  shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX);
  shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT);
  shader->loadShaderSource("PhongVertex","shaders/ShaderVert.glsl");
  shader->loadShaderSource("PhongFragment","shaders/ShaderFrag.glsl");

  shader->compileShader("PhongVertex");
  shader->compileShader("PhongFragment");
  shader->attachShaderToProgram("PhongShader","PhongVertex");
  shader->attachShaderToProgram("PhongShader","PhongFragment");


  shader->linkProgramObject("PhongShader");
  shader->use("PhongShader");

  shader->registerUniform("PhongShader","MVP");

  shader->setUniform("light.position",ngl::Vec3(50,40,100));
  shader->setShaderParam3f("light.La",0.5,0.5,0.5);
  shader->setShaderParam3f("light.Ld",0.9,0.9,0.9);
  shader->setShaderParam3f("light.Ls",0.05,0.05,0.05);

  glEnable(GL_DEPTH_TEST); // for removal of hidden surfaces

  //cloth object created in class header
  //initialize the cloth
  myCloth.init();
  //create triangles for the mesh
  createTris(myCloth.getTriCount());
  //point and line size are specified for wireframe and pointview modes
  glPointSize(4);
  glLineWidth(0.3);

}
Beispiel #28
0
void VehicleAi::OnTick() {
	if (!game_->GetVehicle() || !game_->GetVehicle()->IsLoaded() ||
		!game_->GetLevel() || !game_->GetLevel()->IsLoaded() ||
		game_->GetFlybyMode() != Game::kFlybyInactive) {
		return;
	}

	const cure::TimeManager* _time = GetManager()->GetGameManager()->GetTimeManager();
	const int mode_run_delta_frame_count = _time->GetCurrentPhysicsFrameDelta(mode_start_frame_);
	const float mode_run_time = _time->ConvertPhysicsFramesToSeconds(mode_run_delta_frame_count);
	const float aim_distance = AIM_DISTANCE;

	float strength = 1.0f;
	const vec3 _position = game_->GetVehicle()->GetPosition();
	const vec3 _velocity = game_->GetVehicle()->GetVelocity();
	switch (mode_) {
		case kModeFindBestPath:
		case kModeFindPathOffElevator: {
			float start_time = 0.5f;
			if (active_path_ != -1) {
				// Synchronize all paths.
				Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
				start_time = _path->GetCurrentInterpolationTime();
				active_path_ = -1;
			}
			log_.Headlinef("Trying to find new path... starting iterating from  %.2f.", start_time);
			vec3 elevator_direction;
			if (mode_ == kModeFindPathOffElevator) {
				game_->GetVehicle()->SetEnginePower(0, 0);
				game_->GetVehicle()->SetEnginePower(2, -strength);	// Negative = use full brakes, not only hand brake.
				const cure::Elevator* _nearest_elevator;
				const vec3 elevator_position = GetClosestElevatorPosition(_position, _nearest_elevator);
				if (elevator_position.GetDistanceSquared(_position) > ELEVATOR_TOO_CLOSE_DISTANCE*ELEVATOR_TOO_CLOSE_DISTANCE) {
					log_.AHeadline("Fell off elevator while looking for get-off route. Looking for somewhere else to go.");
					SetMode(kModeFindBestPath);
					return;
				}
				elevator_direction = _nearest_elevator->GetVelocity().GetNormalized(0.5f);
			}
			float best_path_distance = 1000000;
			std::vector<PathIndexLikeliness> relevant_paths;
			bool lifting_towards_goal = false;
			const int path_count = game_->GetLevel()->QueryPath()->GetPathCount();
			for (int x = 0; x < path_count; ++x) {
				bool current_lifting_towards_goal = false;
				Spline* _path = game_->GetLevel()->QueryPath()->GetPath(x);
				_path->GotoAbsoluteTime(start_time);
				float _likeliness = 1;
				const float nearest_distance = GetClosestPathDistance(_position, x, &_likeliness)/SCALE_FACTOR/2;
				log_.Infof(" - Path %2i is %2.2f units away.", x, nearest_distance);
				if (mode_ == kModeFindPathOffElevator) {
					if (_path->GetCurrentInterpolationTime() > 0.7f) {
						// This path is probably the one I used to get ON the elevator (or one
						// just like it from another direction), we're not using that!
						log_.AInfo("   (Not relevant, too close to path end.)");
						continue;
					} else {
						const float towards_distance = GetClosestPathDistance(_position+elevator_direction, x)/SCALE_FACTOR/2;
						if (towards_distance < nearest_distance) {
							current_lifting_towards_goal = true;
							if (!lifting_towards_goal) {
								lifting_towards_goal = true;
								best_path_distance = 1000000;
							}
						}
					}
				}
				if (!current_lifting_towards_goal && lifting_towards_goal) {
					// This elevator isn't heading in the right direction, but at least one other is.
					continue;
				}
				PathIndexLikeliness pl;
				pl.path_index_ = x;
				pl.likeliness_ = _likeliness;
				pl.distance_ = nearest_distance;
				relevant_paths.push_back(pl);
				if (nearest_distance < best_path_distance) {
					best_path_distance = nearest_distance;
				}
			}
			// Sort out those that are too far away.
			float total_likeliness = 0;
			std::vector<PathIndexLikeliness>::iterator x;
			for (x = relevant_paths.begin(); x != relevant_paths.end();) {
				if (x->distance_ < best_path_distance+2.0f) {
					total_likeliness += x->likeliness_;
					++x;
				} else {
					x = relevant_paths.erase(x);
				}
			}
			if (mode_ == kModeFindPathOffElevator) {
				if (best_path_distance > 5 || relevant_paths.size() != 1) {
					if (relevant_paths.size() == 1) {
						// Point wheels in the right direction for us to get off safely.
						Spline* _path = game_->GetLevel()->QueryPath()->GetPath(relevant_paths[0].path_index_);
						const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
						const vec3 wanted_direction = _path->GetValue() - _position;
						const float angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
						game_->GetVehicle()->SetEnginePower(1, angle*0.5f);
					}
					log_.Headlinef("On elevator: too long distance to path %.1f, or too many paths %u.", best_path_distance, relevant_paths.size());
					if (best_path_distance > 15) {
						const cure::Elevator* _nearest_elevator;
						const vec3 nearest_lift_position = GetClosestElevatorPosition(_position, _nearest_elevator);
						if (nearest_lift_position.GetDistanceSquared(_position) > ELEVATOR_TOO_CLOSE_DISTANCE*ELEVATOR_TOO_CLOSE_DISTANCE) {
							// DUCK!!! We fell off!
							log_.AHeadline("Was on elevator: I'm far from the elevator, so must've fallen off!");
							SetMode(kModeFindBestPath);
						}
					}
					if (mode_run_time >= 20) {
						log_.AHeadline("On elevator: been here too long, getting off!");
						SetMode(kModeFindBestPath);
					}
					return;
				}
				log_.Headlinef("Getting off elevator: distance to path %.1f.", best_path_distance);
			}
			deb_assert(!relevant_paths.empty());
			if (relevant_paths.empty()) {
				return;
			}
			const float picked_likeliness = Random::Uniform(0.0f, total_likeliness);
			total_likeliness = 0;
			for (x = relevant_paths.begin(); x != relevant_paths.end(); ++x) {
				const float next_likeliness = total_likeliness + x->likeliness_;
				if (picked_likeliness >= total_likeliness && picked_likeliness <= next_likeliness) {
					active_path_ = x->path_index_;
					break;
				}
				total_likeliness = next_likeliness;
			}
			if (active_path_ < 0) {
				active_path_ = relevant_paths[Random::GetRandomNumber() % relevant_paths.size()].path_index_;
			}
			Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
			const float wanted_distance = aim_distance;
			float step = wanted_distance * _path->GetDistanceNormal();
			if (step + _path->GetCurrentInterpolationTime() > 1) {
				step = 1 - _path->GetCurrentInterpolationTime();
			}
			_path->StepInterpolation(step);
			// Fetch ending position.
			const float t = _path->GetCurrentInterpolationTime();
			_path->GotoAbsoluteTime(END_PATH_TIME);
			elevator_get_on_position_ = _path->GetValue();
			_path->GotoAbsoluteTime(t);

			log_.Headlinef("Picked path %i (%i pickable."), active_path_, relevant_paths.size());
			if (mode_ == kModeFindPathOffElevator) {
				SetMode(kModeGetOffElevator);
			} else {
				SetMode(kModeHeadingBackOnTrack);
			}
		} break;
		case kModeHeadingBackOnTrack: {
			if (mode_run_delta_frame_count%5 == 2) {
				const float velocity_scale_factor = std::min(1.0f, _velocity.GetLength() / 2.5f);
				Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
				const float current_time = _path->GetCurrentInterpolationTime();
				const float nearest_path_distance = GetClosestPathDistance(_position, active_path_, 0, 1);
				if (nearest_path_distance > 3.0f) {
					// First verify that we haven't ended up under path somehow. We do that by checking
					// steepness, since pure Z-distance may be big when going over ditches.
					const vec3 path_position = _path->GetValue();
					const float steepness = (path_position.z - _position.z) / nearest_path_distance;
					//log_.Infof("Checking steepness, nearest path distance is %.3f, steepness is %.3f.", nearest_path_distance, steepness);
					if (steepness > 0.6f) {
						log_.Infof("Searching for new, better path, we seem to have ended up under the path. Beneath a bridge perhaps? Nearest path is %.2f, steepness is %.2f.", nearest_path_distance, steepness);
						SetMode(kModeFindBestPath);
						return;
					}
				}
				_path->GotoAbsoluteTime(current_time);
				if (nearest_path_distance < SCALE_FACTOR * OFF_COURSE_DISTANCE * velocity_scale_factor) {
					// We were able to return to normal, keep on running.
					SetMode(kModeNormal);
					return;
				}
				/*else if (nearest_path_distance > SCALE_FACTOR * OFF_COURSE_DISTANCE * velocity_scale_factor * 5) {
					// We're far off, perhaps we fell down from a plateu.
					active_path_ = -1;
					SetMode(kModeFindBestPath);
					return;
				}*/
				else if (mode_run_time > 7.0f) {
					SetMode(kModeFindBestPath);
					return;
				}
			}
		}
		// TRICKY: fall through.
		case kModeNormal:
		case kModeGetOnElevator:
		case kModeGetOffElevator: {
			if (mode_ == kModeGetOnElevator) {
				if (mode_run_time > 4.5) {
					log_.Headlinef("Something presumably hinders me getting on the elevator, back square one. (mode run time=%f"), mode_run_time);
					SetMode(kModeFindBestPath);
					return;
				}
				const cure::Elevator* _nearest_elevator;
				const vec3 nearest_lift_position = GetClosestElevatorPosition(elevator_get_on_position_, _nearest_elevator);
				if (nearest_lift_position.z > _position.z+0.5f) {
					log_.AHeadline("Couldn't get on in time, going back to waiting.");
					SetMode(kModeWaitingForElevator);
					return;
				}
			}

			if (mode_ != kModeHeadingBackOnTrack && mode_ != kModeGetOnElevator && mode_run_delta_frame_count%20 == 19) {
				const float _distance = GetClosestPathDistance(_position);
				if (_distance > SCALE_FACTOR * TOTALLY_OFF_COURSE_DISTANCE) {
					log_.AHeadline("Fell off something. Trying some new path.");
					SetMode(kModeFindBestPath);
					return;
				}
				const float velocity_scale_factor = ((mode_ == kModeNormal)? 1.0f : 3.0f) * Math::Clamp(_velocity.GetLength() / 2.5f, 0.3f, 1.0f);
				if (_distance > SCALE_FACTOR * OFF_COURSE_DISTANCE * velocity_scale_factor) {
					log_.AHeadline("Going about my way, but got offside somehow. Heading back.");
					SetMode(kModeHeadingBackOnTrack);
					return;
				}
			}

			Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
			vec3 target = _path->GetValue();

			// Check if vehicle stopped. That would mean either crashed against something or too steep hill.
			if (mode_run_delta_frame_count%7 == 4 && game_->GetVehicle()->GetHealth() > 0) {
				if (QueryVehicleHindered(_time, _velocity)) {
					const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
					const vec3 wanted_direction = target-_position;
					const float forward_angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
					// Amplify angle to be either full left or full right.
					const float angle = (forward_angle < 0)? -1.0f : 1.0f;
					game_->GetVehicle()->SetEnginePower(1, -angle);
					SetMode(kModeBackingUp);
					return;
				}
			}

			// Are we heading towards an elevator?
			if (mode_ != kModeGetOnElevator && mode_ != kModeGetOffElevator && _path->GetType() == "to_elevator") {
				if (_path->GetDistanceLeft() <= ELEVATOR_WAIT_DISTANCE) {
					if (elevator_get_on_position_.GetDistanceSquared(_position) <= ELEVATOR_WAIT_DISTANCE*ELEVATOR_WAIT_DISTANCE) {
						log_.AHeadline("Normal mode close to end of path to elevator, changing mode.");
						SetMode(kModeWaitingForElevator);
						return;
					}
				}
			}

			// Did we just pass (fly by?) the goal?
			if (mode_run_delta_frame_count%3 == 0) {
				const vec3 goal_direction = game_->GetGoal()->GetPosition() - _position;
				if (::fabs(goal_direction.z) < 2 &&
					goal_direction.GetLengthSquared() < ELEVATOR_FAR_DISTANCE*ELEVATOR_FAR_DISTANCE &&
					_velocity.GetLengthSquared() < 6*6) {
					const vec3 vehicle_direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
					const float delta_angle = ::fabs(LEPRA_XY_ANGLE(goal_direction, vehicle_direction));
					if (delta_angle >= PIF-PIF/4 && delta_angle <= PIF+PIF/4) {
						log_.AHeadline("Passed goal, it's right behind me!");
						SetMode(kModeBackingUpToGoal);
						return;
					}
				}
			}

			// Step target (aim) ahead.
			{
				const float actual_distance2 = target.GetDistanceSquared(_position);
				const float max_aim_factor = (mode_ == kModeGetOffElevator)? 1.0f : 1.5f;
				const float wanted_distance = aim_distance * Math::Clamp(_velocity.GetLength() / 2.5f, 0.5f, max_aim_factor);
				if (actual_distance2 < wanted_distance*wanted_distance) {
					const float move_ahead = wanted_distance*1.1f - ::sqrt(actual_distance2);
					_path->StepInterpolation(move_ahead * _path->GetDistanceNormal());
					log_volatile(log_.Debugf("Stepping %f (=%f m from %f."), move_ahead*_path->GetDistanceNormal(), move_ahead, _path->GetCurrentInterpolationTime()));
				}

				// Check if we're there yet.
				const float t = _path->GetCurrentInterpolationTime();
				_path->GotoAbsoluteTime(1.0f);
				const float target_distance = (mode_ == kModeGetOnElevator)? ON_ELEVATOR_DISTANCE : ON_GOAL_DISTANCE + game_->GetVehicle()->GetForwardSpeed()/4;
				if (IsCloseToTarget(_position, target_distance)) {
					const bool towards_elevator = (_path->GetType() == "to_elevator");
					if (towards_elevator) {
						if (mode_ == kModeGetOnElevator) {
							SetMode(kModeOnElevator);
							return;
						} else if (mode_ != kModeGetOffElevator) {
							// We got off track somewhere, try to shape up!
							log_.AHeadline("Normal mode target wrapped on our way to an elevator, changing mode.");
							SetMode(kModeWaitingForElevator);
							return;
						}
					} else {
						SetMode(kModeStoppingAtGoal);
						return;
					}
				}
				_path->GotoAbsoluteTime(t);

				target = _path->GetValue();
			}

			const float get_off_delay_time = 0.4f;
			if (!(mode_ == kModeGetOffElevator && mode_run_time < get_off_delay_time)) {
				// Move forward.
				game_->GetVehicle()->SetEnginePower(0, +strength);
				game_->GetVehicle()->SetEnginePower(2, 0);
			}

			// Steer.
			const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
			const vec3 wanted_direction = target-_position;
			float angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
			if (mode_ == kModeGetOffElevator) {
				// Aborting too early might cause us to stop, waiting for the next ride in mid-air.
				const float get_off_distance = GetClosestElevatorRadius() + ELEVATOR_GOT_OFF_EXTRA_DISTANCE;
				vec2 elevator_get_off2d(elevator_get_off_position_.x, elevator_get_off_position_.y);
				vec2 position2d(_position.x, _position.y);
				log_.Infof("ElevatorGetOff (%f;%f, pos (%f;%f)"), elevator_get_off2d.x, elevator_get_off2d.y, position2d.x, position2d.y);
				if (elevator_get_off2d.GetDistanceSquared(position2d) > get_off_distance*get_off_distance) {
					SetMode(kModeNormal);
				}
				angle *= 2;	// Make steering more powerful while getting off.
			}
			game_->GetVehicle()->SetEnginePower(1, +angle);
			last_average_angle_ = Math::Lerp(last_average_angle_, angle, 0.5f);

			// Check if we need to slow down.
			const float high_speed = SCALE_FACTOR * 2.7f;
			const float abs_angle = ::fabs(angle);
			if (_velocity.GetLengthSquared() > high_speed*high_speed) {
				if (abs_angle > 0.2f) {
					float factor = 0.10f;
					game_->GetVehicle()->SetEnginePower(2, abs_angle*factor + _velocity.GetLength()*factor*0.1f);
				} else if (_path->GetCurrentInterpolationTime() >= DOUBLE_OFF_END_PATH_TIME &&
					IsCloseToTarget(_position, SLOW_DOWN_DISTANCE)) {
					game_->GetVehicle()->SetEnginePower(2, 0.2f);
				}
			}
		} break;
		case kModeBackingUp: {
			// Brake or move backward.
			const bool is_moving_forward = (game_->GetVehicle()->GetForwardSpeed() > 0.1f*SCALE_FACTOR);
			game_->GetVehicle()->SetEnginePower(0, is_moving_forward? 0.0f : -strength);
			game_->GetVehicle()->SetEnginePower(2, is_moving_forward? strength :  0.0f);

			const float back_time = 1.7f;
			if (!is_moving_forward && mode_run_time > back_time) {
				SetMode(kModeHeadingBackOnTrack);
				return;
			}
		} break;
		case kModeBackingUpToGoal: {
			vec3 wanted_direction = game_->GetGoal()->GetPosition() - _position;
			const float distance2 = wanted_direction.GetLengthSquared();
			if (distance2 <= ON_GOAL_DISTANCE*ON_GOAL_DISTANCE) {
				Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
				_path->GotoAbsoluteTime(END_PATH_TIME);
				SetMode(kModeStoppingAtGoal);
				return;
			} else if (distance2 >= TOTALLY_OFF_COURSE_DISTANCE*TOTALLY_OFF_COURSE_DISTANCE) {
				SetMode(kModeFindBestPath);
				return;
			}

			// Brake or move backward.
			const bool is_moving_forward = (game_->GetVehicle()->GetForwardSpeed() > 0.1f*SCALE_FACTOR);
			game_->GetVehicle()->SetEnginePower(0, is_moving_forward? 0.0f : -strength);
			game_->GetVehicle()->SetEnginePower(2, is_moving_forward? strength :  0.0f);

			// Turn steering wheel.
			const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
			float angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
			angle += (angle < 0)? +PIF : -PIF;
			angle *= 3;
			game_->GetVehicle()->SetEnginePower(1, -angle);

			if (mode_run_time > 15) {
				log_.AHeadline("Not getting back to goal. F**k it.");
				SetMode(kModeRotateOnTheSpot);
				return;
			}
		} break;
		case kModeFlee: {
			// Pedal to the metal.
			game_->GetVehicle()->SetEnginePower(0, +strength);
			game_->GetVehicle()->SetEnginePower(1, 0);
			game_->GetVehicle()->SetEnginePower(2, 0);
			if (mode_run_time > 3.0f) {
				SetMode(kModeFindBestPath);
				return;
			}
		} break;
		case kModeStoppingAtGoal:
		case kModeAtGoal: {
			Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
			if (!IsCloseToTarget(_position, ON_GOAL_DISTANCE)) {
				// If either already stopped at goal, OR stopped but at the wrong spot.
				if (mode_ != kModeStoppingAtGoal || game_->GetVehicle()->GetForwardSpeed() < 0.5f*SCALE_FACTOR) {
					_path->GotoAbsoluteTime(DOUBLE_OFF_END_PATH_TIME);	// Close to end, but not at end.
					SetMode(kModeHeadingBackOnTrack);
					return;
				}
			}
			if (mode_ != kModeAtGoal) {
				SetMode(kModeAtGoal);
			}
			// Brake!
			game_->GetVehicle()->SetEnginePower(0, 0);
			game_->GetVehicle()->SetEnginePower(2, -strength);	// Negative = use full brakes, not only hand brake.
		} break;
		case kModeWaitingForElevator: {
			if (mode_run_time > 25.0f) {
				log_.AHeadline("Movin' on, I've waited for the elevator too long.");
				SetMode(kModeFlee);
				return;
			}
			if (::fabs(last_average_angle_) > 0.1f) {
				strength *= SMOOTH_BRAKING_FACTOR;	// Smooth braking when turning, we can always back up if necessary.
			}
			const float elevator_distance2 = elevator_get_on_position_.GetDistanceSquared(_position);
			if (elevator_distance2 < ELEVATOR_TOO_CLOSE_DISTANCE*ELEVATOR_TOO_CLOSE_DISTANCE) {
				log_.AHeadline("Got too close to the elevator stop position, backing up.");
				// Back up parallel to the spline direction.
				const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
				Spline* _path = game_->GetLevel()->QueryPath()->GetPath(active_path_);
				const vec3 wanted_direction = _path->GetSlope();
				const float angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
				game_->GetVehicle()->SetEnginePower(1, +angle);
				const bool is_moving_forward = (game_->GetVehicle()->GetForwardSpeed() > 0.1f*SCALE_FACTOR);
				game_->GetVehicle()->SetEnginePower(0, is_moving_forward? 0.0f : -strength);
				game_->GetVehicle()->SetEnginePower(2, is_moving_forward? strength :  0.0f);

				const cure::Elevator* _nearest_elevator;
				vec3 _nearest_lift_position2d;
				float _elevator_xy_distance2_to_elevator_stop;
				const bool is_elevator_here = HasElevatorArrived(_nearest_elevator, _position.z, _nearest_lift_position2d, _elevator_xy_distance2_to_elevator_stop);
				if (is_elevator_here) {
					SetMode(kModeGetOnElevator);
				} else if (QueryVehicleHindered(_time, _velocity)) {
					last_average_angle_ = (Random::Uniform(0.0f, 1.0f) > 0.5f)? +2.0f : -2.0f;
					SetMode(kModeRotateOnTheSpot);
				}
				return;
			}
			if (::fabs(elevator_get_on_position_.z-_position.z) >= 3 ||
				elevator_distance2 > ELEVATOR_FAR_DISTANCE*ELEVATOR_FAR_DISTANCE) {
				log_.AHeadline("Somehow got away from the elevator wait position, doing something else.");
				SetMode(kModeFindBestPath);
				return;
			}

			// Check that we're headed towards the elevator center.
			if (_velocity.GetLengthSquared() < 0.5f) {
				vec3 up(0, 0, 1);
				up = game_->GetVehicle()->GetOrientation() * up;
				if (up.z > 0.7f) {
					const vec3 _direction = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
					const vec3 wanted_direction = elevator_get_on_position_ - _position;
					const float angle = LEPRA_XY_ANGLE(wanted_direction, _direction);
					if (::fabs(angle) > PIF/12) {
						rotate_angle_ = -angle;
						SetMode(kModeRotateOnTheSpotWaiting);
						return;
					}
				}
			}

			const cure::Elevator* _nearest_elevator;
			vec3 _nearest_lift_position2d;
			float _elevator_xy_distance2_to_elevator_stop;
			if (HasElevatorArrived(_nearest_elevator, _position.z, _nearest_lift_position2d, _elevator_xy_distance2_to_elevator_stop)) {
				vec3 velocity_xy = _nearest_elevator->GetVelocity();
				bool try_get_on = false;
				// Check if elevator is on it's way out.
				if (IsVertical(velocity_xy)) {
					try_get_on = true;
				} else {
					velocity_xy.x *= 0.1f;
					velocity_xy.y *= 0.1f;
					velocity_xy.z  = 0;
					if (_elevator_xy_distance2_to_elevator_stop+0.1f >= elevator_get_on_position_.GetDistanceSquared(_nearest_lift_position2d+velocity_xy)) {
						try_get_on = true;
					}
				}
				if (try_get_on) {
					log_.AInfo("Elevator here - getting on!");
					SetMode(kModeGetOnElevator);
					return;
				} else {
					log_.AInfo("Waiting for elevator: not getting on, since elevator is departing!");
				}
			}

			game_->GetVehicle()->SetEnginePower(1, 0);
			// Brake!
			game_->GetVehicle()->SetEnginePower(0, 0);
			game_->GetVehicle()->SetEnginePower(2, -strength);	// Negative = use full brakes, not only hand brake.
		} break;
		case kModeOnElevator: {
			strength *= SMOOTH_BRAKING_FACTOR;	// Smooth braking, we can always back up if necessary.

			// Brake!
			game_->GetVehicle()->SetEnginePower(0, 0);
			game_->GetVehicle()->SetEnginePower(1, 0);
			game_->GetVehicle()->SetEnginePower(2, -strength);	// Negative = use full brakes, not only hand brake.

			// Check if elevator departed.
			const float minimum_velocity2 = 0.5f*0.5f;
			if (mode_run_time > 0.7f && _velocity.GetLengthSquared() > minimum_velocity2) {
				const cure::Elevator* _nearest_elevator;
				const vec3 nearest_lift_position = GetClosestElevatorPosition(elevator_get_on_position_, _nearest_elevator);
				if (nearest_lift_position.z > _position.z+0.2f) {
					// Crap, we missed it!
					log_.AHeadline("Must have missed the elevator (it's not close!), waiting for it again!");
					SetMode(kModeWaitingForElevator);
					return;
				}
				// Vehicle speed check not enouch (bouncy wheels), so check elevator speed too.
				vec3 elevator_velocity = _nearest_elevator->GetVelocity();
				if (elevator_velocity.GetLengthSquared() > minimum_velocity2) {
					const bool is_horizontal = !IsVertical(elevator_velocity);
					const vec3 _direction = is_horizontal? elevator_velocity : game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
					rotate_angle_ = -GetRelativeDriveOnAngle(_direction);
					if (::fabs(rotate_angle_) > PIF/6 || is_horizontal) {
						if (is_horizontal) {
							rotate_angle_ = (rotate_angle_ < 0)? -1.3f : +1.3f;
						}
						SetMode(kModeRotateOnTheSpotDuring);
						return;
					}
					SetMode(kModeFindPathOffElevator);
					return;
				}
			} else if (mode_run_time > 4.5f) {
				// Crap, we missed it!
				log_.AHeadline("Must have missed the elevator (I'm still here!), waiting for it again!");
				SetMode(kModeWaitingForElevator);
				return;
			}

			if (mode_run_time > 0.8f) {
				// Check if we should adjust pos.
				const vec3 forward = game_->GetVehicle()->GetOrientation() * vec3(0,1,0);
				const float dist = elevator_get_on_position_.GetDistanceSquared(_position);
				if (dist > elevator_get_on_position_.GetDistanceSquared(_position+forward)) {
					game_->GetVehicle()->SetEnginePower(0, +strength);
					game_->GetVehicle()->SetEnginePower(2, 0);
				} else if (dist > elevator_get_on_position_.GetDistanceSquared(_position-forward)) {
					game_->GetVehicle()->SetEnginePower(0, -strength);
					game_->GetVehicle()->SetEnginePower(2, 0);
				}
			}
		} break;
		case kModeRotateOnTheSpot:
		case kModeRotateOnTheSpotDuring:
		case kModeRotateOnTheSpotWaiting: {
			float angle = rotate_angle_;
			const float min_angle = 0.3f;
			if (::fabs(angle) < min_angle) {
				angle = (angle < 0)? -min_angle : +min_angle;
			}
			float steer_end_time = 0.4f;
			float forward_end_time = steer_end_time + 0.9f;
			float other_steer_end_time = forward_end_time + steer_end_time;
			float period = other_steer_end_time + 0.8f;

			// A monster truck's steering impared.
			angle *= 2;
			steer_end_time = 0.7f;
			forward_end_time = steer_end_time + 0.7f;
			other_steer_end_time = forward_end_time + steer_end_time;
			period = other_steer_end_time + 1.0f;
			strength *= SMOOTH_BRAKING_FACTOR;
			if (mode_ == kModeRotateOnTheSpotWaiting) {
				const cure::Elevator* _nearest_elevator;
				vec3 _nearest_lift_position2d;
				float _elevator_xy_distance2_to_elevator_stop;
				if (HasElevatorArrived(_nearest_elevator, _position.z, _nearest_lift_position2d, _elevator_xy_distance2_to_elevator_stop)) {
					log_.AHeadline("Elevator arrived while rotating on the spot, getting on instead!");
					SetMode(kModeGetOnElevator);
					return;
				}
			}
			// Finish this rotation show if we're getting there.
			const int iterations = (mode_ == kModeRotateOnTheSpotWaiting)? 1 : 2;
			if (mode_run_time > iterations*period+steer_end_time) {
				game_->GetVehicle()->SetEnginePower(0, 0);
				game_->GetVehicle()->SetEnginePower(1, -angle);
				game_->GetVehicle()->SetEnginePower(2, -1);
				if (mode_ == kModeRotateOnTheSpot) {
					SetMode(kModeHeadingBackOnTrack);
				} else if (mode_ == kModeRotateOnTheSpotDuring) {
					SetMode(kModeFindPathOffElevator);
				} else {
					SetMode(kModeWaitingForElevator);
				}
				return;
			}
			for (int x = 0; x < iterations+1; ++x) {
				const float base = x*period;
				if (mode_run_time >= base && mode_run_time < base+steer_end_time) {
					// Brake and turn in "forward direction".
					game_->GetVehicle()->SetEnginePower(0, 0);
					game_->GetVehicle()->SetEnginePower(1, -angle);
					game_->GetVehicle()->SetEnginePower(2, -strength);
					break;
				} else if (mode_run_time >= base+steer_end_time && mode_run_time < base+forward_end_time) {
					// Drive forward.
					game_->GetVehicle()->SetEnginePower(0, +strength);
					game_->GetVehicle()->SetEnginePower(2, 0);
					break;
				} else if (mode_run_time >= base+forward_end_time && mode_run_time < base+other_steer_end_time) {
					// Brake and turn in "backward direction".
					game_->GetVehicle()->SetEnginePower(0, 0);
					game_->GetVehicle()->SetEnginePower(1, +angle);
					game_->GetVehicle()->SetEnginePower(2, -strength);
					break;
				} else if (mode_run_time >= base+other_steer_end_time && mode_run_time < base+period) {
					// Drive backward.
					game_->GetVehicle()->SetEnginePower(0, -0.7f*strength);
					game_->GetVehicle()->SetEnginePower(2, 0);
					break;
				}
			}
		} break;
	}
Beispiel #29
0
void jffs2_read_inode (struct inode *inode)
{
	struct jffs2_inode_info *f;
	struct jffs2_sb_info *c;
	struct jffs2_raw_inode latest_node;
	int ret;

	D1(printk(KERN_DEBUG "jffs2_read_inode(): inode->i_ino == %lu\n", inode->i_ino));

	f = JFFS2_INODE_INFO(inode);
	c = JFFS2_SB_INFO(inode->i_sb);

	jffs2_init_inode_info(f);
	
	ret = jffs2_do_read_inode(c, f, inode->i_ino, &latest_node);

	if (ret) {
		make_bad_inode(inode);
		up(&f->sem);
		return;
	}
	inode->i_mode = jemode_to_cpu(latest_node.mode);
	inode->i_uid = je16_to_cpu(latest_node.uid);
	inode->i_gid = je16_to_cpu(latest_node.gid);
	inode->i_size = je32_to_cpu(latest_node.isize);
	inode->i_atime = ITIME(je32_to_cpu(latest_node.atime));
	inode->i_mtime = ITIME(je32_to_cpu(latest_node.mtime));
	inode->i_ctime = ITIME(je32_to_cpu(latest_node.ctime));

	inode->i_nlink = f->inocache->nlink;

	inode->i_blksize = PAGE_SIZE;
	inode->i_blocks = (inode->i_size + 511) >> 9;
	
	switch (inode->i_mode & S_IFMT) {
		jint16_t rdev;

	case S_IFLNK:
		inode->i_op = &jffs2_symlink_inode_operations;
		break;
		
	case S_IFDIR:
	{
		struct jffs2_full_dirent *fd;

		for (fd=f->dents; fd; fd = fd->next) {
			if (fd->type == DT_DIR && fd->ino)
				inode->i_nlink++;
		}
		/* and '..' */
		inode->i_nlink++;
		/* Root dir gets i_nlink 3 for some reason */
		if (inode->i_ino == 1)
			inode->i_nlink++;

		inode->i_op = &jffs2_dir_inode_operations;
		inode->i_fop = &jffs2_dir_operations;
		break;
	}
	case S_IFREG:
		inode->i_op = &jffs2_file_inode_operations;
		inode->i_fop = &jffs2_file_operations;
		inode->i_mapping->a_ops = &jffs2_file_address_operations;
		inode->i_mapping->nrpages = 0;
		break;

	case S_IFBLK:
	case S_IFCHR:
		/* Read the device numbers from the media */
		D1(printk(KERN_DEBUG "Reading device numbers from flash\n"));
		if (jffs2_read_dnode(c, f->metadata, (char *)&rdev, 0, sizeof(rdev)) < 0) {
			/* Eep */
			printk(KERN_NOTICE "Read device numbers for inode %lu failed\n", (unsigned long)inode->i_ino);
			up(&f->sem);
			jffs2_do_clear_inode(c, f);
			make_bad_inode(inode);
			return;
		}			

	case S_IFSOCK:
	case S_IFIFO:
		inode->i_op = &jffs2_file_inode_operations;
		init_special_inode(inode, inode->i_mode,
				   old_decode_dev((je16_to_cpu(rdev))));
		break;

	default:
		printk(KERN_WARNING "jffs2_read_inode(): Bogus imode %o for ino %lu\n", inode->i_mode, (unsigned long)inode->i_ino);
	}

	up(&f->sem);

	D1(printk(KERN_DEBUG "jffs2_read_inode() returning\n"));
}
static void VibeOSKernelLinuxTerminateTimer(void)
{
    VibeOSKernelLinuxStopTimer();
    if (VibeSemIsLocked(&g_hMutex)) up(&g_hMutex);
}