2011年6月20日 星期一

crecord

class crecord extends crecord_NullObject {

    var $model;
    var $table;
    var $row;

    var $id;

    function crecord()
    {
        $this->model = NULL;
        $this->table = "";

        $this->_common_init();
    }

    function _common_init( $id = NULL )
    {
        $this->row = NULL;
        $this->id = $id;

        if( $id != NULL )
            $this->load($id);
    }

    function init( &$model , $table, $id = NULL)
    {
        $this->model = &$model;
        $this->table = $table;

        $this->_common_table();
        $this->load($id);
    }

    function equal($record)
    {
        foreach($record->row as $key => $value)
        {

            if( $this->getField($key) != $value )
                    return false;
        }
        return true;
    }


    function reuse($id = NULL)
    {
        $this->_common_init($id);
    }

    function loadlast( $key = null , $value = null)
    {
        $id = $this->model->select_max('id', $key, $value);
        $this->load($id);
    }


    function _common_table()
    {
        $this->model->init($this->table);
    }

    function load($id = NULL)
    {
         return $this->loadwithfield("id", $id);
    }

    function loadwithfield($field, $value)
    {
        $this->_common_table();
        $this->reuse();

        if( $field == NULL || $value == NULL )
            return;

        $row = $this->model->select_field_row($field,$value);

        return $this->_init_load_field($row);

    }

    function _init_load_field($row)
    {
        if( $row == NULL )
        {
            $this->id = NULL;
            return;
        }

        $this->id = $row->id;
        $this->setrow($row);

        return $this->row;
    }

    function load2($field ='id',$value=NULL)
    {
        return $this->loadwithfield($field, $value);

    }

    function is_update()
    {
        return $this->id != NULL;
    }

    function save()
    {
        if( $this->row == NULL )
            return;

        $this->_common_table();
        if( $this->id == NULL )
        {
           $this->id = $this->model->insert($this->row);
           return $this->id;
        }
        else
        {
           $this->model->update($this->id, $this->row);
           return $this->id;
        }

    }

    function delete($id = null)
    {
        $this->_common_table();


        if( $id != null )
            $this->load($id);

        if( $this->id == NULL )
            return;

        $this->model->delete($this->id);
        return $this->id;
    }

    function getField($field)
    {
        if( $field == "id" )
        {
            return $this->id;
        }

        switch( gettype($this->row) )
        {
            case "array":
                return $this->row[$field];

            case "object":
            {
                if( isset($this->row->$field) )
                    return $this->row->$field;
            }

            default:
                return;
        }

        if( is_object($this->row))
                return $this->row->$field;

        if( is_array($this->row))
                return $this->row[$field];
    }


    function setField($field, $value)
    {
        $type = gettype($this->row);
        switch( $type)
        {
            case "array":
                return $this->row[$field] = $value;
            case "object":
            default:
                return $this->row->$field = $value;
        }
    }

    function getrow()
    {
        $row = $this->row;
        if( $row != NULL )
            $row->id = $this->id;
        return $row;
    }

    function setrow($row)
    {
        $this->_tranArr2Obj ($row);
    }

    function _tranArr2Obj($array_row)
    {
        foreach($array_row as $key => $value )
        {
            if( $key == "id" )
                continue;
            $this->setField($key, $value);
        }
    }

    function create_owner()
    {
        return new crecord;
    }

    function isNull()
    {
        return "FALSE";
    }
    
}

mymodel_db

class mymodel_db extends model{

    var $table;

    function mymodel_db(){
        parent::model();

        $this->table = "";
    }

    function init($table)
    {
        $this->table = $table;
    }

    function select($id)
    {
        $row = $this->select_field_row("id", $id);
        return $row;
    }

    function select_query($field, $value)
    {
        $this->db->flush_cache();
        $this->db->where($field , $value);
        
        $query = $this->db->get($this->table);
        return $query;

    }


    function select_field_row($field, $value)
    {
        $query = $this->select_query($field, $value);
        return $query->row();

    }


    function select2($field,$value)
    {

        return $this->select_field_row($field, $value);
    }

    function delete($id){
        $this->db->flush_cache();
        $this->db->where("id",$id);
        $this->db->delete($this->table);

    }

    function insert($row)
    {
        $this->db->flush_cache();
        $this->db->insert($this->table,$row);
        $id = $this->db->insert_id();

        return $id;

    }

    function update($id, $row)
    {
        $this->db->flush_cache();
        $this->db->where("id",$id);
        $this->db->update($this->table,$row);
    }

    function selectall()
    {
        $this->db->flush_cache();
        $query = $this->db->get($this->table);
        return $query;
    }

    function select_all_idTOarr()
    {
        $id_arr = array();
        $this->db->flush_cache();
        $query = $this->db->get($this->table);
        foreach($query->result() as $row)
        {
            $id_arr[] = $row->id;
        }
        return $id_arr;
    }

    function like_query($field, $value)
    {
        $this->db->flush_cache();
        $this->db->like($field , $value);
        $query = $this->db->get($this->table);
        return $query;
    }

    function list_fields()
    {
        $result = $this->db->list_fields($this->table);
        return $result;
    }
}

2011年5月19日 星期四

cweb_grid

class cweb_grid {

    var $column_obj; // 欄位
    var $item_arr; // 項目列
    var $param; // 參數列

    function cweb_grid()
    {

        $this->column_obj = new empty_object;
        $this->item_arr = array();
        $this->param = array();
        
    }


    function _pre_html()
    {
        $param_str = "";
        foreach($this->param as $key => $value )
        {
            $param_str .= " {$key}=\"{$value}\" ";
        }

        $result = "<table " . $param_str . " >";

        return $result;

    }

    function _after_html()
    {
        return "</table>";
    }

    function _arr2obj($row)
    {
        return $row;
    }

    function _proc_row($row)
    {
        $result = "";
        foreach($this->column_obj as $key => $value)
        {
            if( !isset($row->$key) )
                $result .= "<td ></td>";
            else
                $result .= "<td >{$row->$key}</td>";
        }

        $result = "<tr> {$result} </tr>";

        return $result;

    }

    function _proc_column()
    {
        return $this->_proc_row($this->column_obj);

    }

    function _proc_item()
    {

        $result = "";
        foreach($this->item_arr as $item)
        {
            $result .= $this->_proc_row($item);
        }

        return $result;
    }

    function insert_column($key, $text)
    {
        $this->column_obj->$key = $text;
    }

    function insert_item($row)
    {

        $obj = $this->_arr2obj($row);
        $this->item_arr[] = $obj;

    }

    function add_param($key, $value)
    {
        $this->param[$key] = $value;
    }

    function outHtml()
    {
        $result = "";
        
        $result .= $this->_pre_html();

        $result .= $this->_proc_column();

        $result .= $this->_proc_item();

        $result .= $this->_after_html();

        return $result;
    }

}

2011年5月18日 星期三

cweb_link

class cweb_link
{
    var $id;
    var $url;
    var $text;
    var $display;
    function cweb_link($id = "")
    {
        $this->id = $id;
        $this->url = null;
        $this->text = null;
        $this->display = null;
    }

    function insert($url=null,$text=null,$display=true)
    {
        if($url == null || $text == null)
            return;
        $this->url = $url;
        $this->text = $text;
        $this->display = $display;
    }

    function outHtml()
    {
        if($this->display==false)
            return "";

        $html = "<a id='{$this->id}' href='{$this->url}'>{$this->text}</a>";
        if($this->id == "")
            $html = "<a href='{$this->url}'>{$this->text}</a>";
        
        return $html;
    }
}

2011年5月17日 星期二

cweb_select

class cweb_select {
    //put your code here

    var $name;
    var $option;
    var $selected;

    function cweb_select($name = "")
    {
        $this->option = array();
        $this->selected = null;
        $this->name = $name;
    }

    function insert($row /*array or object*/ )
    {
        foreach ($row as $key => $value )
        {
            $this->insertItem($key, $value);
        }
    }

    function insert_only_value($row /*array or object*/ )
    {
        foreach ($row as $value )
        {
            $this->insertItem($value, $value);
        }
    }

    function insertItem($value , $text)
    {
        $this->option[$value] = $text;
    }

    function selected($value)
    {
        $this->selected = $value;
    }

    function getText($value)
    {
        return $this->option[$value];
    }

    function outHtml()
    {
        $result = "";


        foreach( $this->option as $value => $text )
        {
            $selected = "";
            if( $this->selected == $value)
                $selected = " selected";

            $result .= "<option value='{$value}'{$selected}>{$text}</option>";
        }

        $result = "<select name='{$this->name}' >{$result}</select>";

        return $result;
    }
}


2010年5月31日 星期一

Non-Virtual Interface (NVI)

class IuGUI : public IuUnknown
{

public:
    void OnDraw(HDC hDC)
    {
        this->OnOwnerDraw(hDC);
    }

private:
    virtual void OnOwnerDraw(HDC hDC) = 0;

};

class CuGUI :
    public IuGUI
{
public:
    CuGUI(void);
    ~CuGUI(void);

    virtual ULONG Release() 
    { 
        delete this;
        return 0;
    }

private:
    virtual void OnOwnerDraw(HDC hDC);
};

2010年5月24日 星期一

how to using CriticalSection

struct CParam
{
    BOOL bActive;
    int nCount;
    CCriticalSection CriticalSection;

    CParam();
};

CParam::CParam()
:bActive(TRUE)
,nCount(0)
{

}

DWORD WINAPI MyThread(LPVOID lpParameter)
{
    CParam *pParam;
    pParam = (CParam*)lpParameter;
    pParam->bActive = TRUE;

    while(1)
    {
        pParam->CriticalSection.Enter();
        ++pParam->nCount;
        pParam->CriticalSection.Leave();
        Sleep(1);
    }

    pParam->bActive = FALSE;

    ExitThread(0);
}



void InitThread()
{
    HANDLE hThread;
    DWORD ThreadId;

    CParam param;
    hThread = CreateThread(NULL, 0, 
        (LPTHREAD_START_ROUTINE)MyThread, (void*)¶m, 0, &ThreadId);

    while(param.bActive == TRUE)
    {
        param.CriticalSection.Enter();
        Sleep(100);
        cout << param.nCount << "\n";
        param.CriticalSection.Leave();
        
    }

    CloseHandle(hThread);
}


int _tmain(int argc, _TCHAR* argv[])
{
    InitThread();
    return 0;
}

define SaveToSQL interface

class ISaveToSQL {
    function GetField()
    {
        echo "hi... go back to study PHP 3 year!";
    }
}
class cucustom extends ISaveToSQL{
    ....

    function GetField()
    {
        $this->field["name"] = $this->name;
        $this->field["tel"] = $this->tel;
        $this->field["address"] = $this->address;

        return $this->field;
    }
}
class CuModelSave extends model
{
    function insertSaveToSQL(/*ISaveToSQL*/ $ISaveToSQL)
    {
        $this->db->insert($this->table_name, $ISaveToSQL->GetField());
    }
}
class custom_sql extends CuModelSave{
    ...
}

2010年5月16日 星期日

Prototype Pattern -- Load User Define Library

function testUnit_CreateCustom()
    {
        $Custom = $this->cucustom->MyClone();
        echo $this->unit->run($Custom != NULL, "is_TRUE", "Create Custom");
        
        if( $Custom == NULL )
            return;
        
        $Custom->Init("Eric", "1234567", "高興路");
        echo $this->unit->run($Custom->name, "Eric", "name");
        echo $this->unit->run($Custom->tel, "1234567", "tel");
        echo $this->unit->run($Custom->address, "高興路", "address");
        
    }

class cucustom {

    var $name;
    var $tel;
    var $address;

    function cucustom($name = "", $tel = "", $address = "")
    {
        $this->Init($name, $tel, $address);
    }

    function MyClone()
    {
        return new cucustom;
    }

    function Init($name = "", $tel = "", $address = "")
    {
        $this->name = $name;
        $this->tel = $tel;
        $this->address = $address;
    }
}

2010年5月12日 星期三

Create General Object From DLL.

// the GUI is a GUI.DLL

// GUI.h


typedef IuGUI* (*LPFN_CREATEGUI)(void);

GUI_API IuGUI* CreateObject(void);
GUI_API IuGUI* CreateObject(void)
{
    return new CuGUI;
}

// CuGUI

class CuGUI :
    public IuGUI
{
public:
    CuGUI(void);
    ~CuGUI(void);

     virtual ULONG Release() 
     { 
        delete this;
        return 0;
     }

    virtual void OnDraw(HDC hDC);
};

// CGUILoadTest

void CGUILoadTest::testDllCreateObject(void)
{

    LPFN_CREATEGUI lpfnCreateGUI = NULL;

    CuDllManager dllGUI;
    BOOL bResult = dllGUI.LoadLibrary(TEXT("GUI.dll"));
    CPPUNIT_ASSERT( bResult != NULL );

    lpfnCreateGUI = (LPFN_CREATEGUI)dllGUI.GetProcAddress(("CreateObject"));
    CPPUNIT_ASSERT( lpfnCreateGUI != NULL );

    IuGUI *pIuGUI = NULL;

    if( lpfnCreateGUI != NULL )
        pIuGUI = lpfnCreateGUI();

    CPPUNIT_ASSERT( pIuGUI != NULL );

    if( pIuGUI != NULL )
        pIuGUI->Release();

}

2010年5月2日 星期日

filedrive - file upload download

class filedrive extends controller{

    function filedrive()
    {
        parent::controller();
        $this->load->model('filedrive_model','FileDrive',true);
        $this->load->library("cudownload");
        $this->load->library("cuupload");
        $this->culogin->onlogin();
    }

    function index($id="")
    {
        $data["downloadlist"] = "";
        if (empty($id))
                $query = $this->FileDrive->file_query();
        else
                $query = $this->FileDrive->tags_like($id);

        foreach($query->result() as $row){
                $filelist["row"] = $row;
                $data["downloadlist"] .= $this->load->view("downloadlist",$filelist,true);
        }
        $dnTable = $this->load->view("downloadtable",$data,true);
        $viewData["body"] = $dnTable;
        $this->_MainFrame($viewData);
    }

    function upload_form(){
        $tags = $this->FileDrive->get_tags();
        $upForm = array("error"=>"");
        $upForm["active_url"] = "filedrive/upload";
        $upLoadform = $this->cuciload->view("upload_form",$upForm,true);
        $tags = $this->cuciload->view("tags",array("tags"=>$tags,),true);
        $backpage = $this->cuciload->view("backpage",array("goback" => "filedrive"),true);
        $viewData["body"] = $backpage.$upLoadform.$tags;
        $this->_MainFrame($viewData);
    }

    function update_form($id){
        $data["row"] = $this->FileDrive->select_file($id);
        $viewData["body"] = $this->load->view("update_form",$data,true).$this->file_tags();
        $this->_MainFrame($viewData);
    }

    function delete_form($id){
        $data["row"] = $this->FileDrive->select_file($id);
        $viewData["body"] = $this->load->view("delete_form",$data,true);
        $this->_MainFrame($viewData);
    }
    
    function file_tags(){
        $tags = $this->FileDrive->get_tags();
        return $this->cuciload->view("tags",array("tags"=>$tags,),true);
    }

    function update($id){
        $this->FileDrive->update($id);
        redirect("filedrive","location");
    }

    function delete($id){
        $row = $this->FileDrive->select_file($id);
        $this->FileDrive->delete_file($id);
        unlink("./uploads/".$row->file_name.$row->file_ext);
        redirect("filedrive","location");
    }


    function IsUpload($result){
        $data = $this->upload->data();
        $data["true_name"] = $result["true_name"];
        $data["file_date"] = date("Y-m-d");
        $data["file_time"] = date("H:i:s");
        $data["file_tag"] = $this->FileDrive->write_sql($data);
        $data["is_img"]= lang("NO")."</li>";
        if($data["is_image"])
        {
            $data["is_img"] = $this->load->view("is_image",$data,true);
        }

        return $data;
    }

    function Upload()
    {
        if ( empty($_FILES["userfile"]["name"]) )
                redirect("filedrive/upload_form", "location");
        $result = $this->FileDrive->filename();

        $this->cuupload->InitUploadLib_($result["file_name"]);

        if ( ! $this->upload->do_upload())
        {
            $data["body"] = $this->upload->display_errors()."<br>".anchor("filedrive","return file upload!");
        }
        else
        {
            $susess_data = $this->IsUpload($result);
            redirect("filedrive","location");
        }
        $this->_MainFrame($data);
    }

    function _MainFrame($frame)
    {
        $data = $this->_Tag_List();
        $frame["leftmenu"] = $this->load->view("leftmenu",$data,true);
        $frame["submenu"] = $this->load->view("submenu","",true);
        $this->csmainframe->view($frame);
    }

    function _Tag_List(){
        $tags = array();
        $query =$this->FileDrive->get_tags();

        foreach($query->result() as $row){
                $number = $this->FileDrive->count_tags_like($row->id);
                $tags[] = anchor("filedrive/index/".$row->id, $row->tags . " ( ".$number ." ) ");
        }

        $query_all = $this->FileDrive->tags_like("");
        $data["all_num"] = $query_all->num_rows();

        $notags_num = $this->FileDrive->tags_like("null");
        $data["notags_num"] = $notags_num->num_rows();
        $data["tag"] = $tags;
        return $data;
    }

    function download($id){
        $result = $this->FileDrive->download($id);
        $this->cudownload->DownLoadEx($result, "./uploads/");
    }

}


2010年4月22日 星期四

login extends controller

class login extends controller{

    function login()
    {
        parent::controller();
    }

    function index()
    {
        $this->load->view("login");
    }

    function chklogin()
    {
        $this->culogin->login($_POST["account"],$_POST["password"]);
        $this->culogin->islogin();
    }

    function logout(){
        $this->session->unset_userdata("login");
        redirect("main","location");
    }
}

2010年4月21日 星期三

CuLogin -- Login base on CodeIgniter Library

class CuLogin {

    function CuLogin()
    {
        $this->Login_Information();
    }

    function Login_Information(){
        $this->login_account = "useric";
        $this->login_password = "password";
    }

    function chk_login($account,$password){
        if (($account == $this->login_account) && ($password == $this->login_password))
            return true;
        return false;
    }

    function login($account = "",$password = ""){
        $CI = &get_instance();
        $CI->session->set_userdata("login",$this->chk_login($account,$password));
    }

    function islogin(){
        $CI = &get_instance();
        if ($CI->session->userdata("login"))
            redirect("bulletin","location");
        redirect("login","location");
    }

    function onlogin(){
        $CI = &get_instance();
        if (!$CI->session->userdata("login"))
            redirect("main","location");
    }


}



2010年4月16日 星期五

weblink -- view

# delete_form.php
<a href="javascript:history.go(-1)"><?=lang("BACK")?></a> <?=anchor("weblink/delete_link/".$row->id,lang("DELETE"))?>
<table>
    <tr>
        <td><?=lang("LINK").lang("DESCRIPTION")?></td>
        <td><?=$row->link_des?></td>
    </tr>
    <tr>
        <td><?=lang("LINK").lang("WEB")?></td>
        <td>http://<?=$row->weblink?></td>
    </tr>
</table>

# edit_form.php
<?=form_open("weblink/{$action}")?>
<table>
    <tr>
        <td><?=lang("LINK").lang("DESCRIPTION")?></td>
        <td><input type="text" name="link_des" size="40" maxlength="64" value="<?=$row->link_des?>" /></td>
    </tr>
    <tr>
        <td><?=lang("LINK").lang("WEB")?></td>
        <td>http://<input type="text" name="weblink" size="40" maxlength="256" value="<?=$row->weblink?>" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" value="<?=lang("SUBMIT")?>"></td>
    </tr>
</table>
</form>


# showlink.php

<table border="1">
    <tr>
        <td width="150"><?=lang("LINK").lang("DESCRIPTION")?></td>
        <td width="250"><?=lang("LINK").lang("WEB")?></td>
        <td width="50"><?=lang("EDIT")?></td>
    </tr>
    <?php foreach($query->result() as $row):?>
    <tr>
        <td><?=anchor_popup("http://".$row->weblink,$row->link_des,$atts)?></td>
        <td>http://<?=$row->weblink?></td>
        <td><?=anchor("weblink/edit_form/".$row->id,lang("EDIT"))?> <?=anchor("weblink/delete_form/".$row->id,lang("DELETE"))?></td>
    </tr>
    <?php endforeach;?>
</table>





# submenu.php

<table border="0">
    <tr>
        <td><?=anchor("weblink",lang("VIEW").lang("LINK"))?></td>
        <td><?=anchor("weblink/insert_link_form",lang("INSERT").lang("LINK"))?></td>
    </tr>
</table>

2010年4月15日 星期四

weblink_sql -- model

class weblink_sql extends model{

    function weblink_sql()
    {
        parent::model();
        $database_table = $this->config->item("database_table_name");
        $this->table_name = $database_table."weblink";
    }

    function load_post()
    {
        return array(
            "link_des" => $_POST["link_des"],
            "weblink" => $_POST["weblink"]
        );
    }

    function select($id = ""){
        if($id != "")
            return $this->db->get_where($this->table_name,array("id"=>$id));
        $this->db->order_by("id","desc");
        return $this->db->get($this->table_name);

    }

    function insert()
    {
        $this->db->insert($this->table_name,$this->load_post());
    }

    function update($id)
    {
        $this->db->where("id",$id);
        $this->db->update($this->table_name,$this->load_post());
    }

    function delete($id){
        $this->db->where("id",$id);
        $this->db->delete($this->table_name);
    }

}


2010年4月12日 星期一

weblink - modify web link

class weblink extends controller{

    function weblink()
    {
        parent::controller();
        $this->culogin->onlogin();
        $this->load->model("weblink_sql","WLINK",TRUE);
    }

    function index()
    {
        $data["atts"] = array("width" => "1024");
        $data["query"] = $this->WLINK->select();
        $frame["body"] = $this->load->view("showlink",$data,TRUE);
        $this->_MainFrame($frame);
    }

    function insert_link_form(){
        $data["row"] = array();
        $data["action"] = "insert_link";
        $frame["body"] = $this->load->view("edit_form",$data,TRUE);
        $this->_MainFrame($frame);
    }

    function edit_form($id){
        $query = $this->WLINK->select($id);
        $data["action"] = "update_link/".$id;
        $data["row"] = $query->row();
        $frame["body"] = $this->load->view("edit_form",$data,TRUE);
        $this->_MainFrame($frame);
    }

    function delete_form($id){
        $query = $this->WLINK->select($id);
        $data["row"] = $query->row();
        $frame["body"] = $this->load->view("delete_form",$data,TRUE);
        $this->_MainFrame($frame);
    }

    function insert_link(){
        $this->WLINK->insert();
        $this->_Redirect();
    }

    function update_link($id){
        $this->WLINK->update($id);
        $this->_Redirect();
    }

    function delete_link($id){
        $this->WLINK->delete($id);
        $this->_Redirect();
    }

    function _Redirect(){
        redirect("weblink","location");
    }

    function _MainFrame($frame = ""){
        $frame["submenu"] = $this->load->view("submenu","",TRUE);
        $frame["leftmenu"] ="";
        $this->cuciload->view("mainframework",$frame);
    }
}



2010年2月24日 星期三

CuGLES

class CuGLES : public CuEGL  
{

public:
    void Ortho(double left, double right, double bottom, double top, double Near, double Far);
    void Frustum( double fovy, double aspect, double zNear, double zFar );
    void Viewport(int x, int y, int width, int height);
#if 0
    void DrawArrays(const void *pvlist, const void *pnvlist, const void *ptclist,int stride, int numvertices);
    void DrawElements(const void *pvlist, const void *pnvlist, const void *ptclist,int stride, int numvertices,
        const void *pfaceindex, int numfaceindex);
#endif
    
    CuGLES();
    virtual ~CuGLES();

};


CuGLES::CuGLES()
{

}

CuGLES::~CuGLES()
{

}

#if 0
void CuGLES::DrawArrays(const void *pvlist, const void *pnvlist, const void *ptclist, int stride, int numvertices)
{

    glTexCoordPointer(2, GL_FIXED, stride, ptclist);
    // setup client states
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);    // setup arrays
    // first the vertices
    glVertexPointer(3, GL_FIXED , stride, pvlist);
    glEnableClientState(GL_VERTEX_ARRAY);


    // next the normals
//  glNormalPointer(GL_SHORT, stride, pnvlist);
    glNormalPointer(GL_FIXED , stride, pnvlist);
    glEnableClientState(GL_NORMAL_ARRAY);

    glDrawArrays(GL_TRIANGLES , 0, numvertices);


    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

}


void CuGLES::DrawElements(const void *pvlist, const void *pnvlist, const void *ptclist,int stride, int numvertices,
    const void *pfaceindex, int numfaceindex)
{

    glTexCoordPointer(2, GL_FIXED, stride, ptclist);
    // setup client states
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);


    // setup arrays
    // first the vertices
    glVertexPointer(3, GL_FIXED , stride, pvlist);
    glEnableClientState(GL_VERTEX_ARRAY);


    // next the normals
    glNormalPointer(GL_FIXED , stride, pnvlist);
    glEnableClientState(GL_NORMAL_ARRAY);

    glDrawElements(GL_TRIANGLES , numfaceindex, GL_UNSIGNED_BYTE , pfaceindex);


    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

}
#endif

void CuGLES::Viewport(int x, int y, int width, int height)
{
    glViewport(x,y,width,height);
}

#define PI_     3.14159265358979323846
void CuGLES::Frustum(double fovy, double aspect, double zNear, double zFar)
{
    // 設定投影
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float right, left, top, bottom;
    top = zNear * tan(fovy * PI_ / 180.0 / 2 );
    bottom = -top;
    right = top * aspect;
    left = -right;

    glFrustumx(EGL_FixedFromFloat(left), EGL_FixedFromFloat(right),
        EGL_FixedFromFloat(bottom), EGL_FixedFromFloat(top),
        EGL_FixedFromFloat(zNear), EGL_FixedFromFloat(zFar) );

}

void CuGLES::Ortho(double left, double right, double bottom, double top, double Near, double Far)
{

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthox(
        EGL_FixedFromFloat(left),
        EGL_FixedFromFloat(right),
        EGL_FixedFromFloat(bottom), 
        EGL_FixedFromFloat(top), 
        EGL_FixedFromFloat(Near), 
        EGL_FixedFromFloat(Far));

}


完全不了解為什麼要繼承, 想不起來.

2010年2月23日 星期二

CuEGL

class CuEGL  
{

    int _red_size;
    int _green_size;
    int _bule_size;
    int _alpha_size;

public:

    // 
    void SwapBuffers();


    // 只要有呼叫 Init() 做初始化 就要呼叫 Exit() 
    // 在這裡 解構會自動呼叫
    void Exit();

    // 初始化 EGL
    // Return:  1 有問題初始化失敗   0: 一切正常
    bool Init(NativeWindowType hWnd);

    CuEGL();
    virtual ~CuEGL();

    EGLDisplay  _eglDisplay;
    EGLConfig   _eglConfig;
    EGLSurface  _eglSurface;
    EGLContext  _eglContext;



};

CuEGL::CuEGL()
{

    _eglDisplay = EGL_NO_DISPLAY;
    _eglConfig;
    _eglSurface = EGL_NO_SURFACE;
    _eglContext = EGL_NO_CONTEXT;

    _red_size = 5;
    _green_size = 6;
    _bule_size = 5;
    _alpha_size = 0;


}

CuEGL::~CuEGL()
{

    if( _eglDisplay != EGL_NO_DISPLAY )
        this->Exit();

}


bool CuEGL::Init(NativeWindowType hWnd)
{

    int buffer_size = _red_size + _green_size + _bule_size + _alpha_size;
    EGLint  attrs[] = {
        EGL_ALPHA_SIZE, _alpha_size,
        EGL_RED_SIZE, _red_size,
        EGL_GREEN_SIZE, _green_size,
        EGL_BLUE_SIZE, _bule_size,
        EGL_BUFFER_SIZE, buffer_size,
        EGL_DEPTH_SIZE, 16,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE};

    EGLint  numConfig;
    LONG        lRet = 1; 

    // NOTE: Theres a bunch of stuff we should be doing to release resources
    //       in the case of failure that we're not bothering with atm

    HDC hdc = GetWindowDC((HWND)hWnd);

    // Get the display device


    _eglDisplay = eglGetDisplay(hdc);

    Assert( _eglDisplay != EGL_NO_DISPLAY, L"CuEGL::Init:\n _eglDisplay == EGL_NO_DISPLAY");

    // Initialize the display
    if (!eglInitialize(_eglDisplay, NULL, NULL))
        {  
            Assert(0, L"CuEGL::Init:\n can't Initialize egl");
            return lRet;

        }

    // Obtain the first configuration with a depth buffer
    if (!eglChooseConfig(_eglDisplay, attrs, &_eglConfig, 1, &numConfig))
        { 
            Assert(0, L"CuEGL::Init:\n can't ChooseConfig");
            return lRet; 
        }

    // Create a surface for the main window
    _eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, (NativeWindowType)hWnd, NULL);
    Assert( _eglSurface != EGL_NO_SURFACE, L"CuEGL::Init:\n _eglSurface == EGL_NO_SURFACE");

    // Create an OpenGL ES context
    _eglContext = eglCreateContext(_eglDisplay, _eglConfig, EGL_NO_CONTEXT, NULL);
    Assert( _eglContext != EGL_NO_CONTEXT, L"CuEGL::Init:\n _eglContext == EGL_NO_CONTEXT");


    // Make the context and surface current
    if (!eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext))
        {  
            Assert(0, L"CuEGL::Init:\n can't MakeCurrent");
            return lRet; 
        }

    return 0;

}

void CuEGL::Exit()
{

    // Set the current context to nothing
    eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

    // Free any EGL contexts; should be called per context created
    eglDestroyContext(_eglDisplay, _eglContext);

    // Free any EGL surfaces; should be called per surface created
    eglDestroySurface(_eglDisplay, _eglSurface);

    // Terminate any EGL displays; should be called per display initialized
    eglTerminate(_eglDisplay); 

}

void CuEGL::SwapBuffers()
{

    eglSwapBuffers(_eglDisplay, _eglSurface);

}


好舊的碼了~ 如果有更新會在加上去

2010年2月19日 星期五

CuGPSDevice

class CuGPSDevice : public CuPort  
{
    CuFile m_LogFile;
    CuFile m_CheckLogFile;
    CuFile m_CheckErrorLogFile;
    CuFile m_Error_Message_File;


    DWORD m_dReadDataBufferSize;
    DWORD m_dReadDataBuffseIndex;
    BYTE *m_pReadDataBuffer;

    bool _writeFileCheck(CuFile &File, void *pData, int nSize);

public:
    BOOL CheckReadData(BYTE* pReadData);
    virtual void OnWrite(BYTE *pByte, int nSize);
    virtual void OnRead(BYTE *pByte, int nSize);
    CuGPSDevice();
    virtual ~CuGPSDevice();

};




//

CuGPSDevice::CuGPSDevice()
:m_dReadDataBufferSize(1024)
,m_dReadDataBuffseIndex(0)
,m_pReadDataBuffer(NULL)
{

    m_pReadDataBuffer = new BYTE[m_dReadDataBufferSize];

    CuModuleFile mf;
    wstring strLogFile = mf.GetModuleFileName(L"GPS_Log.txt");
    m_LogFile.Open(strLogFile, L"w");


    strLogFile = mf.GetModuleFileName(L"GPS_Check_Log.txt");
    m_CheckLogFile.Open(strLogFile, L"w");

    strLogFile = mf.GetModuleFileName(L"GPS_Check_Error_Log.txt");
    m_CheckErrorLogFile.Open(strLogFile, L"w");


    strLogFile = mf.GetModuleFileName(L"GPS_Error_Message_Log.txt");
    m_Error_Message_File.Open(strLogFile, L"w");
    


}

CuGPSDevice::~CuGPSDevice()
{

}
void CuGPSDevice::OnWrite(BYTE *pByte, int nSize)
{

    unsigned char checksum = 0 ;
    for(int i=0 ; i < nSize; i++)
    {
        checksum ^= pByte[i];
    }
    
    char strCheckSum[2];

    sprintf( strCheckSum, "%x", checksum);
    char pSendStr[2048];
    memset(pSendStr, 0, 2048);

    ::strcat(pSendStr, "$");
    ::strcat(pSendStr, (char*)pByte);

    ::strcat(pSendStr, "*");
    ::strcat(pSendStr, strCheckSum);
    ::strcat(pSendStr, "\x0d");
    ::strcat(pSendStr, "\x0a");
        
    CuPort::OnWrite((BYTE*)pSendStr, strlen(pSendStr));

}

void CuGPSDevice::OnRead(BYTE *pByte, int nSize)
{

    for( int i = 0 ; i < nSize ; i++ )
    {

    
        if( pByte[i] == 0x0a )
        {
            m_pReadDataBuffer[m_dReadDataBuffseIndex++] = pByte[i];
            if( CheckReadData( m_pReadDataBuffer) )
                _writeFileCheck(m_CheckLogFile, (void*)m_pReadDataBuffer , m_dReadDataBuffseIndex);
                m_CheckLogFile.Write(()m_pReadDataBuffer, m_dReadDataBuffseIndex);
            else
                _writeFileCheck(m_CheckErrorLogFile, (void*)m_pReadDataBuffer , m_dReadDataBuffseIndex);
                m_CheckErrorLogFile.Write((void*)m_pReadDataBuffer, m_dReadDataBuffseIndex);


            memset(m_pReadDataBuffer, 0, m_dReadDataBuffseIndex);
            m_dReadDataBuffseIndex = 0;
            continue;
        }

        m_pReadDataBuffer[m_dReadDataBuffseIndex++] = pByte[i];


    }

    {
        m_LogFile.Write((void*)pByte, nSize);
        _writeFileCheck(m_LogFile, (void*)pByte , nSize);
    }


}

BOOL CuGPSDevice::CheckReadData(BYTE* pReadData)
{
    int nSize;
    nSize = strlen((char*)pReadData);

    unsigned char checksumtemp;

    TCHAR checkstr[3];
    checkstr[0] = pReadData[ nSize - 4 ];
    checkstr[1] = pReadData[ nSize - 3 ];
    checkstr[2] = 0;

    swscanf(checkstr, L"%x", &checksumtemp);

    unsigned char checksum = 0 ;
    checksum = 0;
    for(int i=1 ; i < nSize - 5 ; i++)
    {
        checksum ^= pReadData[i];
    }

    return checksum == checksumtemp ? TRUE : FALSE;

}

bool CuGPSDevice::_writeFileCheck(CuFile &File, void *pData, int nSize)
{
    static int nWriteFileResult = 0;
    nWriteFileResult = File.Write(pData, nSize);
    
    bool bResult = (nWriteFileResult == nSize);

    if( !bResult )
    {
        MessageBox(NULL, L"WriteFileError", L"WriteFileError", MB_OK);
        m_Error_Message_File.Write(pData, nSize);
    }
    return bResult;
}

2010年2月18日 星期四

CuImageLoaderBMP



//

class CuImageLoaderBMP : public IuImageLoaderBMP  
{


public:
    CuImageLoaderBMP();
    virtual ~CuImageLoaderBMP();

    //////////////////////////////////////////////////////////////////
    // IuUnknown 公開虛擬界面 
    virtual ULONG Release();

    //////////////////////////////////////////////////////////////////
    // IuImageLoader 公開虛擬界面 
    virtual BOOL LoadFile(IuImageEx *pImageEx, LPCTSTR lpszResourceName);

    enum BMPFORMAT { BMP1555, BMP565};

    void SetBmpFormat(BMPFORMAT bmpFormat);

private:

    BOOL _Load565Bmp(BYTE * pbits);
    BOOL _Load1555Bmp(BYTE * pbits);


//  BOOL _Load565Bmp16(BYTE * pbits);
    BOOL _Load565Bmp24(BYTE * pbits);


    BOOL _Load1555Bmp24(BYTE * ptr);
    BOOL _Load1555Bmp16(BYTE * ptr);
    BOOL _Load1555Bmp8(BYTE * ptr);

private:

    IuImageEx *m_tempImageEx;

    BMPFORMAT m_bmpFormat;
    BITMAPFILEHEADER m_bmfh;
    BITMAPINFOHEADER *m_pInfo;


};


//


CuImageLoaderBMP::CuImageLoaderBMP()
:m_bmpFormat(BMP1555)
,m_pInfo(NULL)
{

}

CuImageLoaderBMP::~CuImageLoaderBMP()
{
    delete [] m_pInfo;
}

ULONG CuImageLoaderBMP::Release()
{
    delete this;
    return 0;
}

void CuImageLoaderBMP::SetBmpFormat(BMPFORMAT bmpFormat)
{
    m_bmpFormat = bmpFormat;
}


BOOL CuImageLoaderBMP::LoadFile(IuImageEx *pImageEx, LPCTSTR lpszResourceName)
{

    delete [] m_pInfo;
    m_pInfo = NULL;

    m_tempImageEx = pImageEx;

    // 需要 Bits 只支援 24 & 16 BIT bmp 圖
    /////////////////////////////////////////////////////////////////////////////////////////////
//  BITMAPINFOHEADER *pInfo = NULL;
    BYTE *pbits;

    CuFile File; 

    if( !File.Open(lpszResourceName, L"rb") )
    {
        Assert(0, L"CuBitmap::LoadFile /n can't open the file");
        return FALSE;
    }


    DWORD readed;
//  BITMAPFILEHEADER bmfh;


    int size = File.GetFileSize();
    if( size > sizeof(BITMAPFILEHEADER) )
    {

        //ReadFile( hfile, &m_bmfh, sizeof(BITMAPFILEHEADER), &readed, 0 );
        readed = File.Read( &m_bmfh,  sizeof(BITMAPFILEHEADER) );

        if(( readed == sizeof(BITMAPFILEHEADER) ) && ( m_bmfh.bfType == 0x4d42 ))
        {

            m_pInfo = (BITMAPINFOHEADER*)(new BYTE[ size - sizeof(BITMAPFILEHEADER) ]);

            Assert(m_pInfo, L"CuBitmap::LoadFile /n not enough memory.");

            File.Read(  m_pInfo, size - sizeof(BITMAPFILEHEADER) );

            // the pInfo type is BITMAPINFOHEADER, 
            // if pInfo add 1 that mean pInfo jump sizeof(BITMAPINFOHEADER)
            pbits = (BYTE*)(m_pInfo+1);

        }
        else
        {
            return FALSE;
        }


    }

    // use Create allocate memory   
    pImageEx->Create(m_pInfo->biWidth, m_pInfo->biHeight, 16);

//  WORD &biBitCount = m_pInfo->biBitCount;

    BOOL bResult = false;

    switch( m_bmpFormat )
    {
    case BMP1555:
        return _Load1555Bmp(pbits);
        break;
    case BMP565:
        return _Load565Bmp(pbits);
        break;
    
    }

    delete [] m_pInfo;
    m_pInfo = NULL;

    return bResult;

}
BOOL CuImageLoaderBMP::_Load565Bmp(BYTE * pbits)
{
    BOOL bResult = false;

    switch( m_pInfo->biBitCount )
    {
    case 24:
        bResult = this->_Load565Bmp24(pbits);
        break;
    case 16:
//      bResult = this->_Load565Bmp16(pbits);
        break;
    case 8:
//      bResult = this->_Load565Bmp8(pbits);
        break;
    default:
        {
            Assert(0, L"CuBitmap::LoadFile /n biBitCount not support.");
        }
        break;
    }

    return bResult;
}
// 
// BOOL CuImageLoaderBMP::_Load565Bmp16(BYTE * pbits)
// {
//  return FALSE;
// }

BOOL CuImageLoaderBMP::_Load565Bmp24(BYTE * pbits)
{

    int nSrcTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 3;
    int nDescTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 2;


    // our copy pointer
    WORD *ptr = (WORD *)m_tempImageEx->Data();

    BYTE r, g, b;

    // Convert From BGR To RGB Format And Copy over
    for( long i = 0; i < nSrcTotalByte; i += 3 ) // Loop Through All Of The Pixels
    {

        BYTE* pPixel=&pbits[i];                 // Grab The Current Pixel

        r = pPixel[2];//br;                                 // copy red
        g = pPixel[1];//bg;                                 // copy green
        b = pPixel[0];//bb;                                 // copy blue

        *(ptr++) = (WORD)( ( r >> 3 << 11) | 
            ( g >> 2 << 5) | 
            ( b >> 3 ) );

    }

    return TRUE;

}


BOOL CuImageLoaderBMP::_Load1555Bmp(BYTE * pbits)
{
    BOOL bResult = false;

    switch( m_pInfo->biBitCount )
    {
    case 24:
        bResult = this->_Load1555Bmp24(pbits);
        break;
    case 16:
        bResult = this->_Load1555Bmp16(pbits);
        break;
    case 8:
        bResult = this->_Load1555Bmp8(pbits);
        break;
    default:
        {
            Assert(0, L"CuBitmap::LoadFile /n biBitCount not support.");
        }
        break;
    }

    return bResult;
}

BOOL CuImageLoaderBMP::_Load1555Bmp8(BYTE * pbits)
{
    int nSrcTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height();
    int nDescTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 2;


    RGBQUAD *pPalette = (RGBQUAD*)(pbits);

    pbits += m_bmfh.bfOffBits - sizeof(BITMAPFILEHEADER) - sizeof(BITMAPINFOHEADER);

    // 來源圖 做 4byte 對齊
    int nSrcJumpByte = 4 - (m_tempImageEx->Width() % 4);
    if( nSrcJumpByte == 4 )
        nSrcJumpByte = 0;

    int nDescJumpByte = 2 - ( (m_tempImageEx->Width() ) % 2 );
    if( nDescJumpByte == 2 )
        nDescJumpByte = 0;

//  nDescJumpByte = 1;


    // our copy pointer
    WORD *ptr = (WORD *)m_tempImageEx->Data();//_bits;

//  BYTE r, g, b;

    // Convert From BGR To RGB Format And Copy over
    //for( long i = 0; i < nSrcTotalByte; i += 1 )   // Loop Through All Of The Pixels

    int i = 0;
    for( int nHeight = 0 ; nHeight < m_tempImageEx->Height() ; nHeight += 1 )
    {
        for( int nWidth = 0 ; nWidth < m_tempImageEx->Width() ; nWidth += 1)
        {

            int nColorIndex = pbits[i++];                   // Grab The Current Pixel
            RGBQUAD Color = pPalette[nColorIndex];

            *(ptr++) = (WORD)( ( Color.rgbRed >> 3 << 10) | 
                                ( Color.rgbGreen >> 3 << 5) | 
                                ( Color.rgbBlue >> 3 ) );

        }
        i += nSrcJumpByte; 
        ptr += nDescJumpByte;

    }



    return TRUE;
}


BOOL CuImageLoaderBMP::_Load1555Bmp16(BYTE * pbits)
{

    int nTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 2;
    BYTE *pData = m_tempImageEx->Data();
    memcpy( pData, pbits, nTotalByte);
    return TRUE;

}

BOOL CuImageLoaderBMP::_Load1555Bmp24(BYTE * pbits)
{

        int nSrcTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 3;
        int nDescTotalByte = m_tempImageEx->Width() * m_tempImageEx->Height() * 2;


        // our copy pointer
        WORD *ptr = (WORD *)m_tempImageEx->Data();

        BYTE r, g, b;

        // Convert From BGR To RGB Format And Copy over
        for( long i = 0; i < nSrcTotalByte; i += 3 ) // Loop Through All Of The Pixels
        {

            BYTE* pPixel=&pbits[i];                 // Grab The Current Pixel
            
            r = pPixel[2];//br;                                 // copy red
            g = pPixel[1];//bg;                                 // copy green
            b = pPixel[0];//bb;                                 // copy blue

            *(ptr++) = (WORD)( ( r >> 3 << 10) | 
                                      ( g >> 3 << 5) | 
                                      ( b >> 3 ) );

        }

    return TRUE;

}


功能複合的太多就會像上面這樣, 整個看起來好像很好用, 但真的要改的時後, 會有點頭大的感覺