Feedjit

Articles for you

Saturday, June 22, 2013

Node.js Server code to Send and Recieve a Json file. Also A Simple Calculator in Node.js Client Server code in node.js Using Express Framework and Socket.IO

App.js code

///////////////
var express = require('express')
  , app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server)
  var file= require('./data');    // Gets the JSON data file
 

server.listen(8765);
console.log("Server Listening on 8765");

// routing
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

    // when the client emits 'sendchat', this listens and executes
    socket.on('sendchat', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit('updatechat', socket.username, data);
    });
    //////////////////////////////////////////////////////////////
    socket.on('add', function (data1,data2) {
   
    var n = parseInt(data1);
    var n2= parseInt(data2);
    socket.emit('fill', n+n2);
    });
    /////////////////////////////////////////////////////////////
    socket.on('readjson',function(datajson){
    datajson=JSON.stringify(file);
    socket.emit('filljs',datajson)
    });
   /////////////////////////////////////////////////////////////
    // when the client emits 'adduser', this listens and executes       
    socket.on('adduser', function (username) {
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        // echo to client they've connected
        socket.emit('updatechat', 'SERVER', 'you have connected');
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        // update the list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
    });
    ///////////////////////
socket.on('uploaded',function(js){
    var file=JSON.stringify(js);
    console.log(file)});
    //////////////////////

    // when the user disconnects.. perform this
    socket.on('disconnect', function () {
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});
//////////////////////////////////////

Html Code of Client named index.html
/////////////////////////////
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<script>
  var socket = io.connect('http://localhost:8765');

  // on connection to server, ask for user's name with an anonymous callback
  socket.on('connect', function(){
    // call the server-side function 'adduser' and send one parameter (value of prompt)
    socket.emit('adduser', prompt("What's your name?"));
  ////////////////////////
  ///////////////////////
   });
 


  // listener, whenever the server emits 'updatechat', this updates the chat body
  socket.on('updatechat', function (username, data) {
    $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
  });
 
  ////////////////////////////////////
  socket.on('fill',function(data){
  $('#txt').append("Result is :"+data);
 });

 socket.on('filljs',function(data){
 //if(data!='')
  $('#jsn').append(data);
 });
  //////////////////////////////////////
 

  // listener, whenever the server emits 'updateusers', this updates the username list
  socket.on('updateusers', function(data) {
    $('#users').empty();
    $.each(data, function(key, value) {
      $('#users').append('<div>' + key + '</div>');
    });
  });

  // on load of page
  $(document).ready(function() {
    // when the client clicks SEND
    $('#datasend').click( function() {
      var message = $('#data').val();
      var message2 = $('#data2').val();
      $('#data').val('');
      $('#data2').val('');
      $('#txt').empty();
      // tell server to execute 'sendchat' and send along one parameter
    //  socket.emit('sendchat', message);
        socket.emit('add',message,message2);
    });
    /////////////////////////////
    $('#rdr').click(function(){
    socket.emit('readjson');
    });
    /////////////////////////////
    // when the client hits ENTER on their keyboard
    $('#data').keypress(function(e) {
      if(e.which == 13) {
        $(this).blur();
        $('#datasend').focus().click();
      }
    });
    /////////////////////////////////////////////
   
    $('#upload').bind("click",function()
    {
        var imgVal = $('#uploadImage').val();
    //  document.getElementById("#uploadImage").files[0];
        socket.emit('uploaded',imgVal);
    });

    ////////////////////////////////////////////
  });

</script>
<html>
<head>
<link rel="stylesheet" type="text/css" href=style.css">
</head>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
  <b>USERS</b>
  <div id="users"></div>
</div>
<div style="float:left;width:400px;height:250px;overflow:scroll-y;padding:10px;">
  <div id="conversation"></div>
  <p>
    <input id="data" style="width:200px;" />
    <input id="data2" style="width:200px"/>
  </p>
  <p>
    <input type="button" id="datasend" value="send";
    style="width:100;height:50" />
    <br>
    <textarea name="text" id="txt"></textarea>
  </p>
  <p>
  <textarea name="jsn" id="jsn" rows="10" cols="50"></textarea></p>
  <input id="rdr" type="button" value="Read Json" style="width:100;height:50"/>
 <!-- <input type="submit" size="40">-->
</div>
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" />
<html>     


WPF Client for Console Server Signalr Server. ASP.NET, Signalr, WPF Client

Main Window.Xaml
////////////////////////////
<Window x:Class="Virtual_Trainer_Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button x:Name="Button1" Content="Send" HorizontalAlignment="Left" Margin="268,35,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
        <Button x:Name="Button2" Content="Connect" HorizontalAlignment="Left" Margin="385,35,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.5,0.5" Click="Button2_Click"/>
        <ListBox x:Name="listBox1" HorizontalAlignment="Left" Height="100" Margin="183,107,0,0" VerticalAlignment="Top" Width="258" RenderTransformOrigin="0.231,0.401"/>
        <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="39" Margin="87,63,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="127"/>
        <TextBox x:Name="textbox2" HorizontalAlignment="Left" Height="80" Margin="29,107,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="149"/>
        <Label x:Name="label_welcome" Content="" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Height="26" Width="149"/>

    </Grid>
</Window>
///////////////////////////////////////////////////////////////////
Main Window.xaml.cs
///////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
//using System.Windows.Threading.Dispatcher;


namespace Virtual_Trainer_Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        IHubProxy proxy;
        HubConnection connection;
        public MainWindow()
        {
            InitializeComponent();
         
       
        }
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            connection = new HubConnection(@"http://localhost:8081/");
            proxy = connection.CreateHubProxy("commHub");
           
          
            proxy.On("broadCastToClients", message =>function(message));
            proxy.On("joined",mess=>this.Dispatcher.Invoke((Action)(()=>label_welcome.Content="Wellcome from Server")));
          
            connection.Error += connection_Error;
            connection.Start().Wait();
        }
        void connection_Error(Exception obj)
        {
            MessageBox.Show(obj.Message);
        }

        void function(string mess)
        {
            this.Dispatcher.Invoke((Action)(() => { textbox2.Text += mess+'\n'; }));
        }
      

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
      
          
            proxy.Invoke("send", textBox1.Text);
            textBox1.Text = null;
       
        }
        private  void UpdateApplicationDataUI(string msg)
        {
            //txtStatus.Text = "test";
            textbox2.Text = msg;
        }
   
       
    }
    public static class ControlExtensions
    {
        public static void Invoke(this Control Control, Action Action)
        {
            Control.Invoke(Action);
        }
    }
}
/////////////////////////////////////////////////////
Run Server
then Client
Click on connect a welcome message will be sent from server to client.
Then any message sent by the client will be received back from the server.

Asp.NET Signalr SelfHost Server in Console. C# Asp.NET Signalr with WPF Client/Console Client/ JavaScript Client

using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;
using System.Threading;

namespace SignalR.Hosting.Self.Samples
{
    class Program
    {
     public  IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CommunicationHub>();
        static public void Tick(Object stateInfo)
        {
           // context.Clients.All.joined("HELLO");
            //Console.WriteLine(context.Clients.ToString());
            Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
           
            //context.Clients.All.joined("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
        }
       // DateTime obje = new DateTime();
       
        public static string message=null;

       // public void Messagetoall()
       //{
       //     context.Clients.All.joined("HeLLO"); }
        static void Main(string[] args)
        {
            TimerCallback callback = new TimerCallback(Tick);
           
            string url = "http://localhost:8081";

            using (WebApplication.Start<Startup>(url))
            {
                Console.WriteLine("Server running on {0}", url);
                Console.WriteLine("Creating timer: {0}\n",
                             DateTime.Now.ToString("h:mm:ss"));
                for (int i = 0; i < 100; i++)
                { Thread.Sleep(50); }
                    //while (true)
                    //{// broadcast obj = new broadcast();
                    //    // obj.Messagetoall();
                    //   // Program prg = new Program();
                    //   // prg.Messagetoall();
                    //}
                // create a one second timer tick
                Timer stateTimer = new Timer(callback, null, 0, 1000);
                // loop here forever
                for (; ; )
                {            }
            }
           
        }
    }
    //public class broadcast:Program
    //{

    //    public void Messagetoall()
    //    { context.Clients.All("HeLLO"); }
    //}

 public   class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Turn cross domain on
            var config = new HubConfiguration { EnableCrossDomain = true };

            // This will map out to http://localhost:8080/signalr by default
            app.MapHubs(config);
        }
    }
    [HubName("commHub")]
    public class CommunicationHub : Hub
    {
        public void send(string message)
        {
            Console.WriteLine(message);
            Clients.Caller.broadCastToClients(message);
        }
        public override Task OnConnected()
        {
            Console.WriteLine("Request from "+Context.ConnectionId+" is recieved");
            return Clients.All.joined(Context.ConnectionId, DateTime.Now.ToString());
        }
        public override Task OnDisconnected()
        {
            Console.WriteLine(Context.ConnectionId + " is Disconnected");
            return Clients.All.left(Context.ConnectionId, DateTime.Now.ToString());
        }
    }
}

Circle Rotation Around X-Axis Y-Axis Z-AXis, C++ Source Code, Opengl, Computer Graphics,

#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include<iostream>
#include<math.h>
using namespace std;
float angle=1.0;
void createcircle () {
// Create the circle in the coordinates origin
const int sides = 20;  // The amount of segment to create the circle
const double radius = 10; // The radius of the circle
 glBegin(GL_LINE_LOOP);
 for (int a = 0; a < 360; a += 360 / sides)
  {
    double heading = a * 3.1415926535897932384626433832795 / 180;
    glVertex2d(cos(heading) * radius, sin(heading) * radius);
  }

glEnd();
}

void RotateCircle(void)
{
  glClear(GL_COLOR_BUFFER_BIT);
  glColor3f(1.0, 1.0, 1.0);

  glMatrixMode(GL_MODELVIEW);

    glTranslatef(0,3,0);
    glRotatef(angle, 1.0, 0.0, 0.0);
    //glRotatef(angle, 0.0, 1.0, 0.0);
    //glRotatef(angle, 0.0, 0.0, 1.0);
    createcircle();
    glutSwapBuffers();

}


int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitWindowSize(500, 500);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
  glutCreateWindow("Assignment# 3");
  glutDisplayFunc(RotateCircle);
  glutIdleFunc(RotateCircle);
  glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0);
  glutMainLoop();
  return(0);
}
// //    #include <GL/gl.h>
//#include <math.h>
//#include <GL/glut.h>
//
//
//typedef struct
//{
//float x;
//float y;
//}CIRCLE;
//
//CIRCLE circle;
//
//float rot = 0;
//
//void createcircle (int k, int r, int h) {
//    glBegin(GL_LINES);
//    for (double i = 0; i < 180; i++)
//    {
//    circle.x = r * cos(i) - h;
//    circle.y = r * sin(i) + k;
//    glVertex3f(circle.x + k,circle.y - h,0);
//   
//    circle.x = r * cos(i + 0.1) - h;
//    circle.y = r * sin(i + 0.1) + k;
//    glVertex3f(circle.x + k,circle.y - h,0);
//    }
//    glEnd();
//}
//
//void display (void) {
//    glClearColor (0.0,0.0,0.0,1.0);
//    glClear (GL_COLOR_BUFFER_BIT);
//    glLoadIdentity();
//    glTranslatef(0,0,-20);
//    glRotatef(rot,0,1,0);
//    glRotatef(rot,1,0,0);
//    glRotatef(rot,0,0,1);
//    glColor3f(1,1,1);
//    createcircle(0,10,0);
//    glRotatef(rot,0,1,0);
//    glRotatef(rot,1,0,0);
//    glRotatef(rot,0,0,1);
//    glColor3f(1,0,0);
//    createcircle(-2,8,-2);
//    glRotatef(rot,0,1,0);
//    glRotatef(rot,1,0,0);
//    glRotatef(rot,0,0,1);
//    glColor3f(0,1,0);
//    createcircle(-1,6,-1);
//    glRotatef(rot,0,1,0);
//    glRotatef(rot,1,0,0);
//    glRotatef(rot,0,0,1);
//    glColor3f(0,0,1);
//    createcircle(2,4,2);
//    glRotatef(rot,0,1,0);
//    glRotatef(rot,1,0,0);
//    glRotatef(rot,0,0,1);
//    glColor3f(0,1,1);
//    createcircle(1,2,1);
//    glutSwapBuffers();
//    rot++;
//}
//
//void reshape (int w, int h) {
//    glViewport (0, 0, (GLsizei)w, (GLsizei)h);
//    glMatrixMode (GL_PROJECTION);
//    glLoadIdentity ();
//    gluPerspective (60, (GLfloat)w / (GLfloat)h, 0.1, 100.0);
//    glMatrixMode (GL_MODELVIEW);
//}
//
//int main (int argc, char **argv) {
//    glutInit (&argc, argv);
//    glutInitDisplayMode (GLUT_DOUBLE);
//    glutInitWindowSize (500, 500);
//    glutInitWindowPosition (100, 100);
//    glutCreateWindow ("A basic OpenGL Window");
//
//    glutDisplayFunc (display);
//    glutIdleFunc (display);
//    glutReshapeFunc (reshape);
//    glutMainLoop ();
//    return 0;
//}

Bresmen's Ellipse Algorithm for Ellipse Drawing in all vertices C++ Source Code OpengL VS-2012 Computer Graphics

#include <glut.h>
using namespace std;
void Start_Line( );
void Set_Graphics( int, int );
//void Line_Algo( int, int, int, int );

int main( int argc, char** argv  )
{
   
    glutInit( &argc, argv );
    glutInitWindowSize( 640,480);
    glutInitWindowPosition( 100, 150 );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
    glutCreateWindow( " Elipse Drawing" );
    glutDisplayFunc( Start_Line );
    Set_Graphics( 100, 100 /*window_width, window_height*/ );
    glutMainLoop( );
    return 0;
}

void drawDot (GLint x, GLint y, GLfloat r, GLfloat g, GLfloat b)
{ glColor3f(r,g,b);
  glBegin (GL_POINTS);
      glVertex2i (x,y);
  glEnd();
}

void symmetricPixels (int x, int y, int xc, int yc, float r, float g, float b)
{ drawDot (xc + x, yc + y, r,g,b);
  drawDot (xc - x, yc + y,r,g,b);
  drawDot (xc + x, yc - y,r,g,b);
  drawDot (xc - x, yc - y,r,g,b);
}

void Ellipse (int a, int b, int xc, int yc, float r, float g, float bl)
{ int aSq,bSq,twoASq,twoBSq,d,dx,dy,x,y;

  aSq = a*a;
  bSq = b*b;
  twoASq = 2*aSq;
  twoBSq = 2*bSq;
  d = bSq - b*aSq + aSq/4;
  dx = 0;
  dy = twoASq*b;
  x = 0;
  y = b;
  symmetricPixels(x,y,xc,yc,r,g,bl);
  while (dx < dy)
  { x++;
    dx += twoBSq;
    if (d >= 0)
    { y--;
      dy -= twoASq;
    }
    if (d < 0)
     d += bSq + dx;
    else
     d += bSq + dx - dy;
    symmetricPixels (x,y,xc,yc,r,g,bl);
  }
  d = (int)(bSq*(x+0.5)*(x+0.5) + aSq*(y-1)*(y-1) -
                 aSq*bSq);
  while (y > 0)
  { y--;
    dy -= twoASq;
    if (d <= 0)
    { x++;
      dx += twoBSq;
    }
    if (d > 0)
         d += aSq - dy;
    else
         d += aSq -dy +dx;
    symmetricPixels(x,y,xc,yc,r,g,bl);
  }
}   
void Set_Graphics( int width, int height )
{
    glClearColor( 1.0, 1.0, 1.0, 0.0 );
    glColor3f( 0.0f, 0.0f, 0.0f );
    glViewport( 0, 0, width, height );
    glMatrixMode( GL_PROJECTION );   
    glLoadIdentity( );
    glEnable( GL_DEPTH_TEST );
    gluPerspective( 45, ( float ) width / height, 1.0, 0 );
    glMatrixMode( GL_MODELVIEW );
    glTranslatef( 0, 0, 5 * ( -height) );
}
void Start_Line( )
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
//    Line_Algo( 5, 8, 29,32 );
//    Circle (40,0,0,1);
    Ellipse (100,30,20,20,0,1,0);
  // glFlush();
    glutSwapBuffers( );
}

Bresmen's Circle Algorithm for Circle Drawing in all vertices C++ Source Code OpengL VS-2012 Computer Graphics

#include <glut.h>
using namespace std;
void Start_Line( );
void Set_Graphics( int, int );
//void Line_Algo( int, int, int, int );

int main( int argc, char** argv  )
{
   
    glutInit( &argc, argv );
    glutInitWindowSize( 600,600);
    glutInitWindowPosition( 100, 150 );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
    glutCreateWindow( " Circle Drawing" );
    glutDisplayFunc( Start_Line );
    Set_Graphics( 100, 100 /*window_width, window_height*/ );
    glutMainLoop( );
    return 0;
}

void drawDot (GLint x, GLint y, GLfloat r, GLfloat g, GLfloat b)
{ glColor3f(r,g,b);
  glBegin (GL_POINTS);
      glVertex2i (x,y);
  glEnd();
}

void circlePoints (int x, int y, float r, float g, float b)
{
  drawDot (x,y,r,g,b);
  drawDot (-x,y,r,g,b);
  drawDot (x,-y,r,g,b);
  drawDot (-x,-y,r,g,b);
  drawDot (y,x,r,g,b);
  drawDot (-y,x,r,g,b);
  drawDot (y,-x,r,g,b);
  drawDot (-y,-x,r,g,b);
}

void Circle (int rad, float r, float g, float b)
{ int x,y,d;
 
  x = 0;
  y = rad;
  circlePoints (x,y,r,g,b);
  d = 1 - rad;
  while (y>x)
  {
    if (d < 0)
     { d += 2*x +3;
    x++;}
    else{
     d += 2*(x-y) + 5;
     x++;y--;}
    circlePoints (x,y,r,g,b);
   
   
  }
}
void Set_Graphics( int width, int height )
{
    glClearColor( 1.0, 1.0, 1.0, 0.0 );
    glColor3f( 0.0f, 0.0f, 0.0f );
    glViewport( 0, 0, width, height );
    glMatrixMode( GL_PROJECTION );   
    glLoadIdentity( );
    glEnable( GL_DEPTH_TEST );
    gluPerspective( 45, ( float ) width / height, 1.0, 0 );
    glMatrixMode( GL_MODELVIEW );
    glTranslatef( 0, 0, 5 * ( -height) );
}
void Start_Line( )
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
//    Line_Algo( 5, 8, 29,32 );
    Circle (100,0,0,1);
    glRotatef(1.0, 1.0, 0.0, 0.0);
    glutSwapBuffers( );
}

Bresmen's Line Algorithm for Line Drawing in all vertices C++ Source Code OpengL VS-2012 Computer Graphics

#include <glut.h>
using namespace std;
void Start_Line( );
void Set_Graphics( int, int );
void Line_Algo( int, int, int, int );

int main( int argc, char** argv  )
{
   
    glutInit( &argc, argv );
    glutInitWindowSize( 800,600);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
    glutCreateWindow( " Line Drawing" );
    glutDisplayFunc( Start_Line );
    Set_Graphics( 100, 100 /*window_width, window_height*/ );
    glutMainLoop( );
    return 0;
}

void DrawPixel( int x_Axis, int y_Axis )
{
    glPointSize( 2.0 );
    glBegin( GL_POINTS );
    glVertex2i( x_Axis, y_Axis );
    glEnd( );
    glFlush( );
}

void Line_Algo( int starting_X, int starting_Y, int ending_X, int ending_Y )
{    int delta, deltaX, deltaY, x_Axis, y_Axis, slope, increment_E, increment_NE;

    if( starting_X > ending_X )
    {
        Line_Algo( ending_X, ending_Y, starting_X, starting_Y );
        return;
    }

    deltaX = ending_X - starting_X;
    deltaY = ending_Y - starting_Y;

    if( deltaY < 0 )
    {
        slope = -1;
        deltaY = - deltaY;
    }
    else
    {
        slope = 1;
    }

    increment_E = 2 * deltaY;
    increment_NE = 2 * ( deltaY - deltaX );

    delta = 2 * deltaY - deltaX;

    x_Axis = starting_X;
    y_Axis = starting_Y;

while( x_Axis < ending_X )
    {
        DrawPixel( x_Axis, y_Axis );

        if( delta < 0 )
        {
            delta += increment_E;
            x_Axis ++;
        }
        else
        {
            delta += increment_NE;
            y_Axis += slope;
            x_Axis++;
        }
       
    }
}
void Set_Graphics( int width, int height )
{
    glClearColor( 1.0, 1.0, 1.0, 0.0 );
    glColor3f( 0.0f, 0.0f, 0.0f );
    gluPerspective( 45, ( float ) width / height, 1.0, 0 );
    glMatrixMode( GL_MODELVIEW );
    glTranslatef( 0, 0, 5 * ( -height) );
}
void Start_Line( )
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    Line_Algo( 0, 0, 40,-40);
    glutSwapBuffers( );
}

Easiest Implementation of Analog Clock in Opengl C++ Source Code. Computer Graphics



  1. // GLclock.c
  2. // By Saqib Khan(International Islamic University Islamabad)
  3. // A openGL example program, displays a 3D clock face
  4. //
  5. // Keyboard inputs: [ESC] = quit
  6. // 'L' = enables/disables lighting
  7. // 'V' = toggle ortho/prespective view

  8. #include <GL/glut.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <math.h>
  12. #include <time.h>

  13. // define glu objects


  14. GLUquadricObj *Cylinder;
  15. GLUquadricObj *Disk;

  16. struct tm *newtime;
  17. time_t ltime;

  18. GLfloat rx, ry, rz, angle;

  19. // lighting
  20. GLfloat LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f };
  21. GLfloat LightDiffuse[]= { 0.5f, 0.5f, 0.5f, 1.0f };
  22. GLfloat LightPosition[]= { 5.0f, 25.0f, 15.0f, 1.0f };
  23. GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };

  24. static int light_state = 1; // light on = 1, light off = 0
  25. static int view_state = 1; // Ortho view = 1, Perspective = 0


  26. void Sprint( int x, int y, char *st)
  27. {
  28.     int l,i;

  29.     l=strlen( st );
  30.     glRasterPos3i( x, y, -1);
  31.     for( i=0; i < l; i++)
  32.         {
  33.         glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st[i]);
  34.     }

  35. }

  36. static void TimeEvent(int te)
  37. {
  38.     int timent;
  39.     int i;

  40.     rx = 30 * cos( angle );
  41.     ry = 30 * sin( angle );
  42.     rz = 30 * cos( angle );
  43.     angle += 0.01;
  44.     if (angle > M_TWOPI) angle = 0;

  45.     glutPostRedisplay();
  46.     glutTimerFunc( 100, TimeEvent, 1);
  47. }

  48. void init(void)
  49. {


  50.    glClearColor (0.0, 0.0, 0.0, 0.0);
  51.    glShadeModel (GL_SMOOTH);
  52.    glEnable(GL_DEPTH_TEST);
  53.    // Lighting is added to scene
  54.    glLightfv(GL_LIGHT1 ,GL_AMBIENT, LightAmbient);
  55.    glLightfv(GL_LIGHT1 ,GL_DIFFUSE, LightDiffuse);
  56.    glLightfv(GL_LIGHT1 ,GL_POSITION, LightPosition);
  57.    glEnable(GL_LIGHTING);
  58.    glEnable(GL_LIGHT1);


  59.    Cylinder = gluNewQuadric();
  60.    gluQuadricDrawStyle( Cylinder, GLU_FILL);
  61.    gluQuadricNormals( Cylinder, GLU_SMOOTH);
  62.    gluQuadricOrientation( Cylinder, GLU_OUTSIDE);
  63.    gluQuadricTexture( Cylinder, GL_TRUE);

  64.    Disk = gluNewQuadric();
  65.    gluQuadricDrawStyle( Disk, GLU_FILL);
  66.    gluQuadricNormals( Disk, GLU_SMOOTH);
  67.    gluQuadricOrientation( Disk, GLU_OUTSIDE);
  68.    gluQuadricTexture( Disk, GL_TRUE);


  69. }

  70. void Draw_gear( void )
  71. {

  72.     int i;
  73.     glPushMatrix();
  74.     gluCylinder(Cylinder, 2.5, 2.5, 1, 16, 16);
  75.     gluDisk(Disk, 0, 2.5, 32, 16);
  76.     glTranslatef(0,0,1);
  77.     gluDisk(Disk, 0, 2.5, 32, 16);
  78.     glPopMatrix();
  79.     for( i = 0; i < 8; i++)
  80.         {
  81.         glPushMatrix();
  82.         glTranslatef( 0.0, 0.0, 0.50);
  83.         glRotatef( (360/8) * i, 0.0, 0.0, 1.0);
  84.         glTranslatef( 3.0, 0.0, 0.0);
  85.         glutSolidCube( 1.0 );
  86.         glPopMatrix();
  87.         }


  88. }

  89. void Draw_clock( GLfloat cx, GLfloat cy, GLfloat cz )
  90. {

  91.   int hour_ticks , sec_ticks;
  92.   glPushMatrix();

  93.   glTranslatef(cx,cy,cz);
  94.   glRotatef( 180, 1.0, 0.0, 0.0);


  95.   glPushMatrix(); // Draw large wire cube
  96.   glColor3f(1.0, 1.0, 1.0);
  97.   glTranslatef( 0.0, 0.0, 6.0);
  98.   glutWireCube(14.0);
  99.   glPopMatrix();

  100.   glPushMatrix(); // Draw clock face
  101.   glTranslatef( 0, 0, 1.0);
  102.   gluDisk(Disk, 0, 6.75, 32, 16);

  103.   glPopMatrix();

  104.   glPushMatrix();// Draw hour hand
  105.   glColor3f(1.0, 0.5, 0.5);
  106.   glTranslatef( 0, 0, 0.0);
  107.   glRotatef( (360/12) * newtime->tm_hour  + (360/60) * (60 / (newtime->tm_min+1)), 0.0, 0.0, 1.0);
  108.   glPushMatrix();
  109.   glTranslatef(0.0, 0.0, 2.0);
  110.   Draw_gear();
  111.   glPopMatrix();
  112.   glRotatef( 90, 1.0, 0.0, 0.0);
  113.   gluCylinder(Cylinder, 0.75, 0, 4, 16, 16);
  114.   glPopMatrix();

  115.   glPushMatrix();// Draw minute hand
  116.   glColor3f(1.0, 0.5, 1.0);
  117.   glTranslatef( 0, 0, 0.0);
  118.   glRotatef( (360/60) * newtime->tm_min, 0.0, 0.0, 1.0);
  119.   glPushMatrix();
  120.   glTranslatef(0.0, 0.0, 3.0);
  121.   glScalef(0.5, 0.5, 1.0);
  122.   Draw_gear();
  123.   glPopMatrix();
  124.   glRotatef( 90, 1.0, 0.0, 0.0);
  125.   gluCylinder(Cylinder, 0.5, 0, 6, 16, 16);
  126.   glPopMatrix();

  127.   glPushMatrix();// Draw second hand
  128.   glColor3f(1.0, 0.0, 0.5);
  129.   glTranslatef( 0, 0, -0.0);
  130.   glRotatef( (360/60) * newtime->tm_sec, 0.0, 0.0, 1.0);
  131.   glPushMatrix();
  132.   glTranslatef(0.0, 0.0, 4.0);
  133.   glScalef(0.25, 0.25, 1.0);
  134.   Draw_gear();
  135.   glPopMatrix();
  136.   glRotatef( 90, 1.0, 0.0, 0.0);
  137.   gluCylinder(Cylinder, 0.25, 0, 6, 16, 16);
  138.   glPopMatrix();


  139.   for(hour_ticks = 0; hour_ticks < 12; hour_ticks++)
  140.       {
  141.       glPushMatrix();// Draw next arm axis.
  142.       glColor3f(0.0, 1.0, 1.0); // give it a color
  143.       glTranslatef(0.0, 0.0, 0.0);
  144.       glRotatef( (360/12) * hour_ticks, 0.0, 0.0, 1.0);
  145.       glTranslatef( 6.0, 0.0, 0.0);
  146.       glutSolidCube(1.0);

  147.       glPopMatrix();
  148.   }
  149.   for(sec_ticks = 0; sec_ticks < 60; sec_ticks++)
  150.      {
  151.        glPushMatrix();
  152.     glTranslatef(0.0, 0.0, 0.0);
  153.     glRotatef( (360/60) * sec_ticks, 0.0, 0.0, 1.0);
  154.     glTranslatef(6.0, 0.0, 0.0);
  155.     glutSolidCube(0.25);
  156.     glPopMatrix();
  157.     }


  158.   glPopMatrix();

  159. }


  160. void display(void)
  161. {

  162.   time(&ltime); // Get time
  163.   newtime = localtime(&ltime); // Convert to local time

  164.   glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  165.   // easy way to put text on the screen.
  166.   glMatrixMode (GL_PROJECTION);
  167.   glLoadIdentity();
  168.   glOrtho(-8.0, 8.0, -8.0, 8.0, 1.0, 60.0);
  169.   glMatrixMode(GL_MODELVIEW);
  170.   glLoadIdentity();
  171.   glDisable(GL_LIGHTING);
  172.   glDisable(GL_COLOR_MATERIAL);

  173.   // Put view state on screen
  174.   glColor3f( 1.0, 1.0, 1.0);
  175.   if (view_state == 0)
  176.       {
  177.       Sprint(-3, -4, "Perspective view");
  178.       }else Sprint(-2, -4, "Ortho view");


  179.       Sprint(-4,-8, asctime(newtime));

  180.   // Turn Perspective mode on/off
  181.   if (view_state == 0)
  182.      {
  183.      glMatrixMode (GL_PROJECTION);
  184.      glLoadIdentity();

  185.      gluPerspective(60.0, 1, 1.0, 60.0);
  186.      glMatrixMode(GL_MODELVIEW);
  187.      glLoadIdentity();
  188.      gluLookAt( rx, 0.0, rz, 0.0, 0.0, -14.0, 0, 1, 0);
  189.      }

  190.     if (light_state == 1)
  191.       {
  192.        glEnable(GL_LIGHTING);
  193.        glEnable(GL_COLOR_MATERIAL);  // Enable for lighing
  194.       }else
  195.       {
  196.       glDisable(GL_LIGHTING);
  197.       glDisable(GL_COLOR_MATERIAL);  // Disable for no lighing
  198.   }

  199. Draw_clock( 0.0, 0.0, -14.0);



  200. glutSwapBuffers();
  201. }

  202. void reshape (int w, int h)
  203. {
  204.    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
  205.    glMatrixMode (GL_PROJECTION);
  206.    glLoadIdentity ();
  207. }

  208. void keyboard (unsigned char key, int x, int y)
  209. {
  210.    switch (key)
  211.    {
  212.          case 'L':
  213.          light_state = abs(light_state - 1);
  214.          break;
  215.       case 'V':
  216.          view_state = abs(view_state - 1);
  217.          break;
  218.       case 27:
  219.          exit(0); // exit program when [ESC] key presseed
  220.          break;
  221.       default:
  222.          break;
  223.    }


  224. }

  225. int main(int argc, char** argv)
  226. {
  227.    glutInit(&argc, argv);
  228.    glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
  229.    glutInitWindowSize (500, 500);
  230.    glutInitWindowPosition (10, 10);
  231.    glutCreateWindow (argv[0]);
  232.    glutSetWindowTitle("GLclock");
  233.    init ();
  234.    glutDisplayFunc(display);
  235.    glutReshapeFunc(reshape);
  236.    glutKeyboardFunc(keyboard);
  237.    glutTimerFunc( 10, TimeEvent, 1);
  238.    glutMainLoop();
  239.    return 0;
  240. }

Thursday, June 6, 2013

Vacuum Cleaner Artificially Intelligent Implementation A.I based with Auto Manual System in C#



                           VACUUM_CLEANER
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dru_Cleaner      //Main Form
{
    public partial class Main_Form : Form
    {
        public Main_Form()
        {
            InitializeComponent();}

    private void button2_Click(object sender, EventArgs e)
        {this.Close();}

    private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int choice = int.Parse(textBox1.Text);
                if (choice == 1)
                {
                    Manual_Form obj = new Manual_Form(); obj.Show();this.Hide();}
                else if (choice == 2)
                {
                Automatic_Form obj = new Automatic_Form();obj.Show();this.Hide(); }
                else if (choice == 3)
                {
               Choice_Random obj = new Choice_Random();obj.Show();this.Hide(); }
                textBox1.Text = null;}
            catch (Exception ex) { MessageBox.Show(ex.Message); }}}}
/////////////////////////////////////      Manual Form
namespace Dru_Cleaner{
    public partial class Manual_Form : Form
    {
        public Manual_Form()
        {
            InitializeComponent();}
      
public string[,] lookup = new string[5,3];
private void button1_Click(object sender, EventArgs e)
        {
         string location, status = null;location = textBox1.Text.ToUpper();
         status =   textBox2.Text.ToUpper();int bound0 = lookup.GetUpperBound(0);
        int bound1 = lookup.GetUpperBound(1);
            for (int j = 0; j < bound0; j++)
            {
 for (int k = 0; k < bound1; k++){
 
if (location == lookup[j, k])
  {
     if (status == lookup[j, ++k]){ MessageBox.Show(lookup[j, ++k]); }}}}
      textBox1.Text = null;textBox2.Text = null;
        }
private void Form1_Load(object sender, EventArgs e){
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";}
private void button2_Click(object sender, EventArgs e){
            this.Close();
            Application.OpenForms[0].Show();}}}
/////////////////////////////////////////
namespace Dru_Cleaner
{
    public partial class Automatic_Form : Form
    {
        public Automatic_Form()
        {
            InitializeComponent();}
public string[,] lookup = new string[5, 3];
private void button2_Click(object sender, EventArgs e)
{
  this.Close();Application.OpenForms[0].Show();}

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = null;button1.Enabled = false;
   int bound0 = lookup.GetUpperBound(0);int bound1 = lookup.GetUpperBound(1);
 for (int j = 0; j <= bound0; j++)
            {
                for (int k = 0; k <= bound1; k++)
             
 textBox1.Text += "   ";textBox1.Text += lookup[j, k];textBox1.Text += "                    ";
 Stopwatch delayWatch = new Stopwatch();
 while (delayWatch.ElapsedMilliseconds < 1200)
                    {
                        delayWatch.Start();
                        Application.DoEvents();
                        delayWatch.Stop();} } textBox1.Text += Environment.NewLine}}
     textBox1.Text += "STOP...! The whole area is now cleaned up";
            button1.Enabled = true;}
        private void Automatic_Form_Load(object sender, EventArgs e)
        {
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";
            lookup[4, 0] = "A"; lookup[4, 1] = "CLEAN"; lookup[4, 2] = "MOVE RIGHT";
        }}}
////////////////////////////   //Random Choic Form
namespace Dru_Cleaner
{
    public partial class Random_Form : Form
    {
        public Random_Form()
        {
            InitializeComponent();
        }
        public string[,] lookup = new string[5, 3];
 private void Random_Form_Load(object sender, EventArgs e)
        {
            lookup[0, 0] = "A"; lookup[0, 1] = "DIRTY"; lookup[0, 2] = "CLEAN";
            lookup[1, 0] = "A"; lookup[1, 1] = "CLEAN"; lookup[1, 2] = "MOVE RIGHT";
            lookup[2, 0] = "B"; lookup[2, 1] = "DIRTY"; lookup[2, 2] = "CLEAN";
            lookup[3, 0] = "B"; lookup[3, 1] = "CLEAN"; lookup[3, 2] = "MOVE LEFT";
        }

 private void button1_Click(object sender, EventArgs e)
        {
    if (textBox1.Enabled==false)
            {
                Random RandNum = new Random();
                int MyRandomNumber = RandNum.Next(4);
                string location, action = null;
                location = lookup[MyRandomNumber, 0];
                action = textBox2.Text.ToUpper();
                int bound0 = lookup.GetUpperBound(0);
                int bound1 = lookup.GetUpperBound(1);
                for (int j = 0; j < bound0; j++)
                {
                    for (int k = 0; k < bound1; k++)
                    {
                        if (location == lookup[j, k])
                        {
                            k++;
                            if (action == lookup[j, ++k])
        { MessageBox.Show("Location:  " + location + "\n" + "State:    " + lookup[j, --k]); }
                        }}}
            }
            else if (textBox2.Enabled == false)
            {
                Random rd = new Random();
                int rnum = rd.Next(4);
                string location, action = null;
                location = textBox1.Text.ToUpper();
                action = lookup[rnum, 2];
                int bound0 = lookup.GetUpperBound(0);
                int bound1 = lookup.GetUpperBound(1);
                for (int j = 0; j < bound0; j++)
                {
                    for (int k = 0; k < bound1; k++)
                    {
                        if (location == lookup[j, k])
                        {
                            k++;
                            if (action == lookup[j, ++k])
        { MessageBox.Show("State:  " + lookup[j, --k] + "\n" + "Action:  " + action); }
                        }
                    }
                }

            }
         textBox1.Text = null;
         textBox2.Text = null;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.OpenForms[1].Show();
        }
    }
}

Read More

Articles for you