3D drawing in Visual Basic.pdf

download 3D drawing in Visual Basic.pdf

of 14

Transcript of 3D drawing in Visual Basic.pdf

  • 8/10/2019 3D drawing in Visual Basic.pdf

    1/14

    WebZIP lets you download complete Web pages or Web sites onto your hard

    disk..Use WebZIP to get a permanent copy of online news articles, e-zines and

    other research material, and quickly find a view them offline anytime.

    WebZIP News

    Upgrade

    Don't Show Ads

    September1998

    3DdrawinginVisualBasic

    byNormBowler

    Youcandownloadthisarticle'ssamplefilesfromourWebsiteaspartofthefilesept98.zip.Gotowww.zdjournals.com/ivb,thenclicktheSourceCodehyperlink.

    IfyouaskedmewhetherornotVisualBasicwasagreatmultimediaplatform,myanswerwouldbe,"Yes,butnotrightoutofthebox."EvenwiththeMediaControlInterface(MCI)objectthatcomesintheprofessionalversionsofVB4and5,andtheGIFandJPGformatsupportinversion5,VisualBasicstilllacksmanyofthefeaturesthatwouldmakeitafirst-classmultimediadeliveryplatform.Gettingbettersupportforimages,animation,and3Drenderingwillcostyou--eitheryourtime(spentwritingcustomfunctionsinVBorWindowsC)oryourmoney(spentonprepackagedlibrariesandcontrolstodothecoolstuff).Ifit'scoolyouwant,wecanatleastsaveyousometime.Inthisarticle,we'll

    introduceyoutotheconceptsbehind3Ddrawing.Then,we'llwalkyouthroughastraightforwardtechniquethatdraws3DlinesinaVBpicturebox,likethoseshowninFigureA.Nextmonth,we'lldemonstratehowtodraw3Dwireframesandfilledshapes.Onceyouhaveourcodeinhand,youcanuseittobuildcustom3Dgraphs,plots,andillustrations.Let'sbeginbyreviewingsomefundamentalaspectsof3Dspacethatareintegraltothisprocess.

    FigureA:We'llshowyouhowtodrawlinesthatlookthree-dimensional.

    Throughthelookingglass

    Inordertomakeapictureboxactlikeawindowintoathree-dimensionalspace,you'llhavetousesomesortofperspective.Towardthisend,you'lldefineavanishingpointinthepicturebox.Then,you'llwriteanalgorithmthatdisplacespointstowardthevanishingpointastheymoveawayfromtheviewer.(Ifyoufindthisterminologyunfamiliar,you'llwanttoreadthearticle"SimplePerspective"inthismonth'sissue.)

    Ofcourse,assoonasyoustartthinkingofaVBpictureboxasawindowinto3Dspace,you'llneedacoordinatesystemtodescribewhatyouseeanddraw.Thecoordinatesystemwillbefamiliartoalgebrastudents:Theorigin--the(0,0,0)point--willlieinthelower-leftcornerofthepicturebox.XvaluesincreaseastheymovetotherightandYvaluesincreaseastheymoveup.Forthethirddimension,you'lluseZ,whichincreasesasitmovesawayfromtheviewer

    intothedepthsofthemonitor.Theplaneoftheboxitself,whichrepresentstheviewer'slocation,hasaZvalueof0.

    FigureBshowsanexamplethatusesthiscoordinatesystem.Thelower-leftcornerofthepictureboxhasthe(X,Y,Z)coordinates(0,0,0);thelower-rightcornerliesat(100,0,0);theupper-leftcornerhasthecoordinates(0,100,0);andtheupper-rightcornerisat(100,100,0).Thefigurealsoshowsthevanishingpointinthecenterofthepicturebox,withcoordinates

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://www.zdjournals.com/ivb,http://www.zdjournals.com/ivb,http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://www.zdjournals.com/ivb,
  • 8/10/2019 3D drawing in Visual Basic.pdf

    2/14

    (X,Y,1000).NotethatweusethevariablesXandYinsteadofnumbersbecausethevanishingpointrepresents allvaluesofXandYwhereZequals1000.We'vepositionedthepointinthecenterofthepictureboxasifitsXandYcoordinateswere(50,50).

    FigureB:Ourcoordinatesystemactsasawindowinto3Dspace.

    ThemostinterestingpartofFigureBisthelinethatrunsfromthelower-rightcorner(100,0,0)tothevanishingpoint(X,Y,1000).ThisisthelineofconvergencethatrepresentsallZvaluesbetween0and1000forpointswithanX,Ycoordinateof(100,0).Ourfiguredemonstratesthatinordertodrawapointinperspective,yousimplydeterminewhereitliesonthelinebetweenthevanishingpointandthepoint's(X,Y)locationonthepictureboxplanewhereZequals0.

    Nowthatyouseethelineonwhichthepointmustfall,thequestionbecomes whereonthelineofconvergencedoyou

    placeaparticularpoint?Thisiswheremyambitionexceedsmymathematicalunderstanding;butI'vedevelopedanalgorithmthatlooksgoodandappearstomakesense.Let'sseehowitworks.

    Anangulara lgorithm

    Therateofchangeinanobject'sapparentpositionisgreatestneartheviewerandbecomesprogressivelylessastheobjectsrecedeintothedistance.So,makingtheamountofconvergencedirectlyproportionaltoitsZdisplacementwon'twork.Instead,ouralgorithmtranslatesapoint'sconvergence backfromthevanishingpoint,proportionaltothesquareofitsZtraveloverthedistancebetweenthevanishingpointandtheplaneofthepicturebox.Whatamouthful!Here'showitworks,inpracticalterms,usingthecoordinatesystemshowninFigureB.

    AnypointwithaZvaluegreaterthanorequaltothevanishingpointdistance(1000)willbeshownatthe

    vanishingpoint.

    ApointwithaZvalueof900hastraveled10percentofthedistancebetweenthevanishingpoint(Zequalto1000)andthepictureboxZplane(Zequalto0).Tenpercent(.10)squaredequals.01,or1percent.So,apointatZequalto900willbetranslated1percentalongthelinebetweenthevanishingpointandthepointonthepictureboxplane.Usingsimilarcalculations,pointswithZvaluesof500,100,and0willappearat25percent(.50squared),81percent(.90squared)and100percent(1.0squared),respectively,ofthedistance

    fromthevanishingpointalongthelineofconvergence,respectively.

    ApointwithaZvalueof-100hastraveled110percentofthedistancefromthevanishingpointtothepicture

    boxplane.Squaring1.10yields1.21,sothepointwillbetranslated121percentalongthelineofconvergence.

    Noticethatthealgorithmletsyoucalculatetranslatedcoordinatesforpointsthatare behindtheviewer'splaneofvision.You'llneedtodothistodrawlineswithoneormoreendpointsoffscreen.

    Asyoucanseefromourexamples,thealgorithmappearstofitreality.The10percentofZtravelnearestthepicture

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    3/14

    boxplaneconverges18percent,whilethe10percentofZtravelnearestthevanishingpointconvergesonly1percent.

    Setupcode

    Now,let'stransformwhatyou'velearnedaboutperspectivedrawingintoasampleformandVBcode.You'llimplement3Ddrawingusingglobalvariablesandcodeattachedtotheform.(Packagingthecodeinaclasslibrarywouldbemoreelegant,butdoingsowouldaddsignificantlytothesizeofthecodeandthescopeofthisarticle.)We'llbeginworkontheprojectthismonthandaddtoitnextmonth.Tobegin,openanewVBproject.Namethedefaultform frm3d,andplaceonitapictureboxnamedpbandabuttonnamedbasic.AssigncaptionsasshowninFigureC.Savetheformasthreedee.frmandtheprojectas threedee.vbp.Nextyou'lladdthecode.

    FigureC:Addapictureboxandabuttontoaforminanewproject.

    Note:Commentreduction

    Becauseofthelengthofourexample'scode,we'veomittedmanyofthecommentlines.However,thesamplefilesavailableatwww.zdjournals.com/ivbcontaincomprehensivecomments.

    Declarations

    ListingAcontainstheglobalvariabledeclarationsyouneedtoenterintofrm3d.Mostofthesevariableshavetodo

    withimplementingthecoordinatesystemandvanishingpoint;theycontainvaluescalculatedfromthepicturebox'spropertiesduringcoordinatesetup.

    ListingA:Globalvariabledeclarations

    OptionExplicit

    'windowconfiguration--pblleft(xmin),

    `pbrright(xmax),pbbbottom(ymin),`pbttop(ymax),pbzzcoordDimpblAsDouble

    DimpbrAsDoubleDimpbbAsDouble

    DimpbtAsDoubleDimpbzAsDouble

    'vanishingpoint--x,y,zcoordinates

    DimvpxAsDoubleDimvpyAsDouble

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://www.zdjournals.com/ivbhttp://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://www.zdjournals.com/ivb
  • 8/10/2019 3D drawing in Visual Basic.pdf

    4/14

    DimvpzAsDouble

    'zdelta--zdistancefrompbplane'tovanishingpointDimzdAsDouble

    Coordinatesetup

    Thesubprocedureinit3dshowninListingBinitializesmostoftheglobalvariables;addthiscodetoyourform.This

    procedureletsyouspecifytheXcoordinateoftheleftsideofthepicturebox,theYcoordinateofthebottomedge,thewidthofthepicturebox,itsZcoordinate,andhowfarintothescenethevanishingpointlies.Forthe

    coordinatesystemdisplayedinFigureB,thecallwouldbeasfollows:

    init3d0,0,100,0,1000

    OurexampleformmakesthiscallinitsLoadeventcode,shownattheendofListingB.

    ListingB:init3dandForm_Loadsubprocedures

    Subinit3d(lAsDouble,bAsDouble,wAsDouble,zAsDouble,vpoffAsDouble)'l=left=xminimum.b=bottom=yminimum.

    'w=width.l+w=xmaximum.z=zofpictureboxplane.vpoff=vanishingpointzoffset.

    'Initializesvarsthatimplementcoordinatesystem.`Setsacustomscaleonpicturebox.

    'pictureboxheightandwidth,inpixelsDimpbhpxAsSingleDimpbwpxAsSingle

    pb.ScaleMode=3'pixelspbhpx=pb.ScaleHeight

    pbwpx=pb.ScaleWidth

    'setcoordinatesforwindow

    pbl=lpbr=l+wpbt=b+((pbhpx/pbwpx)*w)

    pbb=bpbz=z

    'setpictureboxscalepb.ScaleLeft=pblpb.ScaleTop=pbt

    pb.ScaleWidth=pbr-pblpb.ScaleHeight=pbb-pbt

    zd=vpoff

    'initvanishingptcoords,centeredhorizvert

    vpx=(pbl+pbr)*(0.5)vpy=((pbt-pbb)*(0.5))+pbbvpz=pbz+zdEndSub

    PrivateSubForm_Load()'initializecoordinatesysteminit3d0,0,100,0,1000

    EndSub

    Theinit3dproceduresetsacustomscaleforthepictureboxandcalculatesthemaximumYvalueforcorrectaspectratio.Ifyouspecifyawidthof100unitsandyourpictureboxishalfashighasitiswide,themaximumY

    valuewillbe50.Thus,squareswillalwaysbesquare.

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    5/14

    Theargumentstoinit3dallowyoutosetadifferentcoordinatesystemthantheonewe'reusing,aswellasmakingtheperspectiveeffectmoreorlessobvious.Ourvanishingpointis10timesthewidthofthepicturebox.

    DecreasingtheZoffsetwouldmaketheperspectiveeffectmorenoticeable,whichissimilartothelookproducedbyawide-anglelens.

    Thecodealsoplacesthevanishingpointinthecenteroftheimage.Ifyouwishtomovethevanishingpointand

    horizonlinehigheronthescreen,increasetheup/downmultiplier.Valuesgreaterthan.5raisethevanishingpointandmakeitappearthatyou'relookingdownonthescene,ratherthanlookingparalleltotheground.

    3Dlines

    NormallyinVB,you'ddrawalineinapicturebox(pb)byspecifyingtheXandYcoordinatesoftheendpoints,like

    this:

    pb.Line(x1,y1)-(x2,y2)

    Todrawin3D,ontheotherhand,youneedaZcoordinateaswell.Enterintofrm3dthesubprocedureln3d,showninListingC,whosecallisasfollows:

    ln3dx1,y1,z1,x2,y2,z2

    Let'sseehowthissubprocedureworks.

    ListingC:ln3dsubprocedureandcalledfunctions

    Subln3d(ByValx1AsDouble,ByValy1AsDouble,ByValz1AsDouble,ByValx2AsDouble,_ByValy2AsDouble,ByValz2AsDouble)

    `Drawsaperspectivecorrectedline

    DimxaAsDouble

    DimyaAsDoubleDimxbAsDoubleDimybAsDouble

    xa=xtrans(x1,z1)

    ya=ytrans(y1,z1)xb=xtrans(x2,z2)yb=ytrans(y2,z2)

    pb.Line(xa,ya)-(xb,yb)EndSub

    Functionxtrans(ByValxAsDouble,ByValzAsDouble)AsDouble

    `Translates3Dxcoordinateinto2Dpicturebox

    `coordinatebasedonitszdisplacement

    DimzsAsDouble'zscratchDimcpAsDouble'correctionpercentage

    DimsdAsDouble'scratchdelta

    Ifz>=vpzThenxtrans=vpx

    ExitFunctionElsezs=vpz-zcp=(zs/zd)*(zs/zd)sd=vpx-x

    xtrans=vpx-(cp*sd)EndIfEndFunction

    Functionytrans(ByValyAsDouble,ByValzAsDouble)AsDouble

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    6/14

    `Translates3Dycoordinateinto2Dpicturebox

    `coordinatebasedonitszdisplacement

    DimzsAsDouble'zscratch

    DimcpAsDouble'correctionpercentageDimsdAsDouble'scratchdelta

    Ifz>=vpzThen

    ytrans=vpyExitFunction

    Elsezs=vpz-zcp=(zs/zd)*(zs/zd)

    sd=vpy-yytrans=vpy-(cp*sd)EndIf

    EndFunction

    Translationfunctions

    Theactuallinethattheln3dprocedurewilldrawinthepictureboxwillbea2D(X,Y)line--infact,itwillcallpb.Line

    todothejob.Butfirst,itmustcalculatetheconvergenceofthe3Dcoordinatesandtranslatetheminto2Dcoordinatesusingthealgorithmwedescribedearlier.Toperformthischore,ln3dcallstheproceduresxtransandytrans,asshowninListingC;addthemtoyourform.

    Linefunction

    Theln3dproceduredeclaresfourvariablestocontainthetranslated

    (x1,y1)-(x2,y2)

    endpoints,itcallsxtransandytranstoperformthecalculation,anditcallspb.Linetodrawtheline.Tosetthecolor

    andwidthoftheline,modifytheForeColorandDrawWidthpropertiesofthepicturebox.

    Anexample

    Tosee3Dlinedrawinginaction,placethecodefromListingDintheClickeventoftheBasic3DDrawingbutton.Whenyouruntheproject,itwillgeneratethelinesshowninFigureA.

    PrivateSubbasic_Click()'loopcounterDimlpAsDouble

    'initializepictureboxvpy=(pbt+pbb)/2

    pb.Clspb.ForeColor=QBColor(0)

    pb.FillStyle=0pb.FillColor=QBColor(11)pb.DrawWidth=1

    'constantsusedtodrawfloorgridConstxmin=-3000#

    Constxmax=3000#Constzmin=0#Constzmax=1000#

    Constgstep=50#

    'horizonline

    pb.Line(pbl,vpy)-(pbr,vpy)

    'xlines

    Forlp=xminToxmaxStepgstep

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    7/14

    ln3dlp,0,zmin,lp,0,zmaxDoEvents

    Nextlp

    'zlines

    Forlp=zminTozmaxStepgstepln3dxmin,0,lp,xmax,0,lpDoEvents

    Nextlp

    pb.ForeColor=RGB(0,0,0)

    EndSub

    Youcandownloadthisarticle'ssamplefilesfromourWebsiteaspartofthefileoct98.zip.Gotowww.zdjournals.com/ivb,thenclicktheSourceCodehyperlink.

    Thismonth,we'llexpandourprojecttodraw3Dspheres,cubes,andtriangles,aswellasfilledwireframeshapeslikethatshowninFigureA.We'llbuildonthecodewewrotelastmonth,andweassumeyou'veeitherdownloadedorcreatedthesampleproject.

    FigureA:Nifty3Dimageslikethisonewilladdsophisticationtoyourapplications.

    Setupsteps

    Atpresent,thethreedeeforminthethreedeeprojectcontainsapicture boxtodisplay3Ddrawingsandasingle

    commandbutton.Let'sbeginbyopeningtheprojectandaddingtwomorebuttonsnamedfilledandunfilled.GivethesebuttonsthecaptionsFilledWireframeandUnfilledWireframe.Nowwe'llgettoworkdrawing3Dcubesandspheres.

    3Dcubesandspheres

    Yourfirstnew3Dshapeisawireframecube.Ourcubeprocedure,showninListingA,usestheln3dprocedurewepresentedlastmonthtodrawarectangularprism.IttakesminimumandmaximumX,Y,andZvaluesasarguments,thendrawsthe12three-dimensionallinesrequiredtomakeacube.(Aswithlastmonth'scode,we'veremovedmostcommentlinestosavespace.However,thesamplefilescontaincomprehensivecomments.)

    ListingA:Thecubeprocedure

    Subcube(ByValxminAsDouble,ByValxmaxAs_Double,ByValyminAsDouble,ByValymaxAs_Double,ByValzminAsDouble,ByValzmaxAsDouble)

    ln3dxmin,ymin,zmax,xmax,ymin,zmax'backface

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://www.zdjournals.com/ivb,http://www.zdjournals.com/ivb,http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://www.zdjournals.com/ivb,
  • 8/10/2019 3D drawing in Visual Basic.pdf

    8/14

    ln3dxmin,ymin,zmax,xmin,ymax,zmaxln3dxmax,ymin,zmax,xmax,ymax,zmax

    ln3dxmin,ymax,zmax,xmax,ymax,zmax

    ln3dxmin,ymin,zmax,xmin,ymin,zmin'sideedges

    ln3dxmax,ymin,zmax,xmax,ymin,zminln3dxmin,ymax,zmax,xmin,ymax,zminln3dxmax,ymax,zmax,xmax,ymax,zmin

    ln3dxmin,ymin,zmin,xmax,ymin,zmin'frontfaceln3dxmin,ymin,zmin,xmin,ymax,zmin

    ln3dxmax,ymin,zmin,xmax,ymax,zminln3dxmin,ymax,zmin,xmax,ymax,zminEndSub

    Next,you'llenterthecodetocreateasphere.Becausethisimplementationdoesn'tperformshading,representingasphereissimplyamatterofdrawingacirclewithatranslatedcenterpointandaperspective-correctedradius.Enterintothefrm3dformthesp3dsubprocedureshowninListingB,whichtakesfourarguments:theX,Y,andZ

    coordinateofitscenter,anditsradius:

    sp3dx,y,z,radius

    ListingB:Thesp3dsubprocedure

    Subsp3d(ByValx1AsDouble,ByValy1AsDouble,ByValz1AsDouble,ByValrAsDouble)

    DimxaAsDouble'translatedxDimyaAsDouble'translatedyDimxbAsDouble'translatedxforradiusDimcrAsDouble'correctedradiuslength

    xa=xtrans(x1,z1)ya=ytrans(y1,z1)xb=xtrans(x1+r,z1)

    cr=xb-xa

    pb.Circle(xa,ya),cr

    EndSub

    Theprocedureusesxtransandytranswecreatedlastmonthtotranslatethe3Dcenterpointtoa2Dcoordinate,thenaddstheradiustotheXcoordinateofthecenterpointtocalculateapointontherightedgeofthecircle.ThedifferencebetweenthetwotranslatedXcoordinatesistheperspective-correctedradius.

    VBdeterminesthecircle'slinewidthandcolorfromthepicturebox'sDrawWidthandForeColorproperties.Similarly,thefillstyleandcolorcomefromthepicturebox'sFillStyleandFillColorproperties.

    Let'supdatethecodeintheBasic3Ddrawingbuttontodisplay3Dcubesandspheresaswellaslines,asshowninFigureB.AddthecodeshownincolorinListingCatthebeginningandendoftheBasic3DDrawingbutton's

    Clickevent.

    FigureB:Ourcodegeneratesthesesamplespheres,cubes,andlines.

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    9/14

    ListingC:basic_click()

    PrivateSubbasic_Click()DimlpAsDouble

    Dimra(1To8,1To3)AsDoubleDimlp2AsInteger

    DimxAsIntegerDimyAsIntegerDimzAsInteger

    .

    .

    .

    Forlp=700To100Step-100'spheressp3d0,10,lp,10DoEvents

    Nextlp

    pb.ForeColor=QBColor(12)`cubes

    Forlp=0To900Step100cube140,180,100,140,lp,lp+40DoEvents

    Nextlp

    pb.ForeColor=RGB(0,0,0)

    EndSub

    3Dfilledtriangles

    Foryourfinalprimitiveshape,you'llcreatefilledandunfilled3Dtriangles.Butfirst,youmustmakeacoupleof

    additionstotheexistingcode.Addthefollowinglinetotheglobalvariablesintheform'sgeneraldeclarations:

    DimsprAsDouble

    Thisvariableprovidesascaleunit-to-pixelratioforthetrianglefillyou'llcreatelater.Now,addthislinetotheinit3dprocedure:

    spr=(pbt-pbb)/pbhpx

    Thiscodecalculatestheratioyoujustdefined.Thecodeforthetr3dprocedureappearsinListingD,alongwiththecodeforsimpleminandmaxfunctionstheprocedureuses.Thetr3dproceduretakesasargumentstheX,Y,and

    Zcoordinatesofthethreecorners:

    tr3dx1,y1,z1,x2,y2,z2,x3,y3,z3

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    10/14

    ListingD:Thetr3dprocedure

    Subtr3d(ByValx1AsDouble,ByValy1AsDouble,_ByValz1AsDouble,ByValx2AsDouble,_ByValy2AsDouble,ByValz2AsDouble,_

    ByValx3AsDouble,ByValy3AsDouble,_ByValz3AsDouble)

    DimxaAsDouble'translatedcoordsfor3pointsDimyaAsDoubleDimxbAsDoubleDimybAsDoubleDimxcAsDoubleDimycAsDouble

    DimcuryAsDouble'currentyDimyminAsDouble'minimumyfortriangle

    DimymaxAsDouble'maxyfortriangleDimxminAsDouble'minxforscanlineDimxmaxAsDouble'maxxforscanline

    DimstpAsDouble'ystepvalue

    DimbAsBoolean'booleanflagforlinecomparisonDimiyAsDouble'scratchvarsforlinecomparisonDimayAsDoubleDimixAsDoubleDimaxAsDouble

    DimxtmpAsDouble'xinterceptoncurrentline

    'ifdens>1,scanlinestepwillbe

  • 8/10/2019 3D drawing in Visual Basic.pdf

    11/14

    ay=ybix=xa

    ax=xbElseay=ya

    ix=xbax=xaEndIf

    If(cury>=iy)And(cury=iy)And(cury

  • 8/10/2019 3D drawing in Visual Basic.pdf

    12/14

    Nextcury

    'outlines,justincase.(catchesroundingerrors)pb.Line(xa,ya)-(xb,yb),pb.FillColorpb.Line(xa,ya)-(xc,yc),pb.FillColor

    pb.Line(xb,yb)-(xc,yc),pb.FillColorEndSub

    Functionmin(ByValaAsDouble,ByValbAsDouble)IfabThen

    max=aElse

    max=bEndIfEndFunction

    Thisprocedurewilldraweitherfilledorunfilledtriangles.Ifthepicturebox'sFillStylepropertyissetto1

    (Transparent),theproceduretranslatesthethreeendpoints,drawsthethreelines,andexits.IfFillStyleissetto0(Solid)oranyothervalue,theproceduredrawsafilledtriangleinthepicturebox'sfillcolor.

    Thefilledtrianglecodeusesascan-linefilltofilla2Dtriangleusingonlyhorizontallines.Thecodedeterminesthe

    minimumandmaximumYvalueofthethreeendpoints,thenincrementsfromonetotheotherinone-pixelincrements.Atleasttwoofthelineswillhaveintersectionpointsoneachpixelrow.Allthreelineswillhaveapointonapixelrowonlywhenthetriangleincludesahorizontalline.

    Thecodedeterminestheintersectionpoints,drawsahorizontallinefromtheminimumXpointtothemaximumXpoint,thencontinuestothenextpixelrow.WhenthecodereachesthelastYvalue,itwillhavefilledthetriangleusinghorizontallines,withnounfilledpixelsandnopixelfilledmorethanonce.

    Whendevelopingthiscode,Inoticedslightroundingerrorsthatresultedinoccasionalunfilledpixelsattheedgeofthetriangle.Iaddedafewlinesofcodetodrawthetriangleedges,butbeawarethattheresultstillmissesasinglepixelonceinagreatwhile.

    Beyondtriangles

    Filledtrianglesarethebasisforallpolygonfills.Youcanbreakdownarectangleintotwotriangles;morecomplexshapesrequiremoretriangles.Ourfilledtriangleproceduretakesyououtoftheworldofwireframemodelsand

    alittlebitcloserto3Drendering.Ifyou'recarefultodrawyourfilledshapesinreverseZ-order(drawingthefarthestshapefirst),youcanmakeyourwireframemodelsopaquebyperforminghiddensurfaceremoval.

    FigureAshowsanexampleofafilledwireframemodel.Thelumpsandswoopsarethegraphoftheinteractionoftwosinewaves,varyingalongtheXandZaxes.ListingEcontainsthewireframe1procedurethatyieldsthis

    result.

    ListingE:Thewireframe1procedure

    Subwireframe1()DimxAsIntegerDimzAsInteger

    Constpi=3.14159265Constxmin=-400Constxmax=500

    Constzmax=800Constzmin=375Conststp=20'gridsize

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    di 14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    13/14

    Constfac1=250'factor1.sinrateofchangeConstfac2=120'factor2.sinmultiplier

    Constfac3=-170'factor3.gridyoffset

    pb.Cls

    vpy=pbt'setvanishingpointtotopofpicturebox

    pb.FillColor=QBColor(11)'setproperties

    pb.ForeColor=QBColor(0)

    pb.DrawWidth=1

    Forz=zmaxTozminStep(stp*-1)_'drawfrombacktofrontForx=xminToxmaxStepstp_

    'drawfromlefttorightIf(xzmin)And_(pb.FillStyle1)Then

    tr3dx,(Sin(x*pi/fac1)+Sin(z*pi/fac1))_*fac2+fac3,z,x+stp,(Sin((x+stp)*pi/_fac1)+Sin(z*pi/fac1))*fac2+fac3,z,x,_

    (Sin(x*pi/fac1)+_Sin((z-stp)*pi/fac1))*fac2+fac3,z-stp

    tr3dx+stp,(Sin((x+stp)*pi/fac1)+_Sin(z*pi/fac1))*fac2+fac3,z,x,_(Sin(x*pi/fac1)+_

    Sin((z-stp)*pi/fac1))*fac2+fac3,_z-stp,x+stp,(Sin((x+stp)*pi/fac1)+_Sin((z-stp)*pi/fac1))*fac2+fac3,z-stp

    EndIfIfxzminThenln3dx,(Sin(x*pi/fac1)_+Sin(z*pi/fac1))*fac2_

    +fac3,z,x,(Sin(x*pi/fac1)_+Sin((z-stp)*pi/_fac1))*fac2+fac3,z-stp

    EndIfDoEventsNextx

    Nextz

    EndSub

    Miscellaneousfunctions

    Withthebasicframeworkinplace,it'seasytoextendyour3Ddrawingcapabilities.Forinstance,thesamplecodeavailablefromourWebsiteincludesasimpleextension.Thehorizonproceduretakes"groundcolor"and"skycolor"asarguments.Itclearsthepicturebox,thencolorseverythingabovethevanishingpoint'sYvalue"sky"andeverythingatorbelowthevanishingpoint"ground."You'llsoonfindyourselfdevelopingsimilartools.

    Stonesleftunturned

    Istherereallysuchathingasavanishingpoint?No--iftherewere,allthestarsinthenightskywouldconvergeto

    asinglebrightpoint.Avanishingpointisjustaconvenientconstructiontousewhenimplementingperspective,anditworksonlywhenitliesbeyondthefarthestpointyoudraw.

    Alsonotethatwedidn'tdiscusscolorinthesearticles.Oursamplecodeusesonlythestandard16colorsavailablethroughtheqbcolorfunction,butyoucanuseanycolors.However,youmaygetstrangeresultson16-or256-colorsystems,especiallywithlinewidthsof1.

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    di 14 03/12/2014 17.34

    http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...
  • 8/10/2019 3D drawing in Visual Basic.pdf

    14/14

    Conclusion

    Afterworkingthroughourexamples,areyoureadytowriteyourownrenderingengine?Probablynot.Butyou'reboundtothinkofmanywaystousethetechniqueswe'vedemonstratedtodeliver3DgraphsandwireframesinyourVBapplications.Wehopeyou'lluseourexamplesasstartingpointstotakeyourapplicationstothenext

    visuallevel.

    1999MicrosoftCorporation.Allrightsreserved.Termsofuse

    [email protected]

    drawing in Visual Basic http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl..

    mailto:[email protected]://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...http://kampol.htc.ac.th/web1/subject/programming2/sheet/vb6/vbarticl...mailto:[email protected]