makepandacore.py 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452
  1. ########################################################################
  2. ##
  3. ## This file, makepandacore, contains all the global state and
  4. ## global functions for the makepanda system.
  5. ##
  6. ########################################################################
  7. import sys,os,time,stat,string,re,getopt,fnmatch,threading,signal,shutil,platform,glob,getpass,signal
  8. import subprocess
  9. from distutils import sysconfig
  10. if sys.version_info >= (3, 0):
  11. import pickle
  12. import _thread as thread
  13. import configparser
  14. else:
  15. import cPickle as pickle
  16. import thread
  17. import ConfigParser as configparser
  18. SUFFIX_INC = [".cxx",".cpp",".c",".h",".I",".yxx",".lxx",".mm",".rc",".r"]
  19. SUFFIX_DLL = [".dll",".dlo",".dle",".dli",".dlm",".mll",".exe",".pyd",".ocx"]
  20. SUFFIX_LIB = [".lib",".ilb"]
  21. VCS_DIRS = set(["CVS", "CVSROOT", ".git", ".hg", "__pycache__"])
  22. VCS_FILES = set([".cvsignore", ".gitignore", ".gitmodules", ".hgignore"])
  23. STARTTIME = time.time()
  24. MAINTHREAD = threading.currentThread()
  25. OUTPUTDIR = "built"
  26. CUSTOM_OUTPUTDIR = False
  27. THIRDPARTYBASE = None
  28. THIRDPARTYDIR = None
  29. OPTIMIZE = "3"
  30. VERBOSE = False
  31. LINK_ALL_STATIC = False
  32. TARGET = None
  33. TARGET_ARCH = None
  34. HAS_TARGET_ARCH = False
  35. TOOLCHAIN_PREFIX = ""
  36. ANDROID_ABI = None
  37. ANDROID_TRIPLE = None
  38. ANDROID_API = None
  39. SYS_LIB_DIRS = []
  40. SYS_INC_DIRS = []
  41. DEBUG_DEPENDENCIES = False
  42. # Is the current Python a 32-bit or 64-bit build? There doesn't
  43. # appear to be a universal test for this.
  44. if sys.platform == 'darwin':
  45. # On OSX, platform.architecture reports '64bit' even if it is
  46. # currently running in 32-bit mode. But sys.maxint is a reliable
  47. # indicator.
  48. if sys.version_info >= (3, 0):
  49. host_64 = (sys.maxsize > 0x100000000)
  50. else:
  51. host_64 = (sys.maxint > 0x100000000)
  52. else:
  53. # On Windows (and Linux?) sys.maxint reports 0x7fffffff even on a
  54. # 64-bit build. So we stick with platform.architecture in that
  55. # case.
  56. host_64 = (platform.architecture()[0] == '64bit')
  57. # On Android, get a list of all the public system libraries.
  58. ANDROID_SYS_LIBS = []
  59. if os.path.exists("/etc/public.libraries.txt"):
  60. for line in open("/etc/public.libraries.txt", "r"):
  61. line = line.strip()
  62. ANDROID_SYS_LIBS.append(line)
  63. ########################################################################
  64. ##
  65. ## Visual C++ Version (MSVC) and Visual Studio Information Map
  66. ##
  67. ########################################################################
  68. MSVCVERSIONINFO = {
  69. (10,0): {"vsversion":(10,0), "vsname":"Visual Studio 2010"},
  70. (11,0): {"vsversion":(11,0), "vsname":"Visual Studio 2012"},
  71. (12,0): {"vsversion":(12,0), "vsname":"Visual Studio 2013"},
  72. (14,0): {"vsversion":(14,0), "vsname":"Visual Studio 2015"},
  73. (14,1): {"vsversion":(15,0), "vsname":"Visual Studio 2017"},
  74. }
  75. ########################################################################
  76. ##
  77. ## Maya and Max Version List (with registry keys)
  78. ##
  79. ########################################################################
  80. MAYAVERSIONINFO = [("MAYA6", "6.0"),
  81. ("MAYA65", "6.5"),
  82. ("MAYA7", "7.0"),
  83. ("MAYA8", "8.0"),
  84. ("MAYA85", "8.5"),
  85. ("MAYA2008","2008"),
  86. ("MAYA2009","2009"),
  87. ("MAYA2010","2010"),
  88. ("MAYA2011","2011"),
  89. ("MAYA2012","2012"),
  90. ("MAYA2013","2013"),
  91. ("MAYA20135","2013.5"),
  92. ("MAYA2014","2014"),
  93. ("MAYA2015","2015"),
  94. ("MAYA2016","2016"),
  95. ("MAYA20165","2016.5"),
  96. ("MAYA2017","2017")
  97. ]
  98. MAXVERSIONINFO = [("MAX6", "SOFTWARE\\Autodesk\\3DSMAX\\6.0", "installdir", "maxsdk\\cssdk\\include"),
  99. ("MAX7", "SOFTWARE\\Autodesk\\3DSMAX\\7.0", "Installdir", "maxsdk\\include\\CS"),
  100. ("MAX8", "SOFTWARE\\Autodesk\\3DSMAX\\8.0", "Installdir", "maxsdk\\include\\CS"),
  101. ("MAX9", "SOFTWARE\\Autodesk\\3DSMAX\\9.0", "Installdir", "maxsdk\\include\\CS"),
  102. ("MAX2009", "SOFTWARE\\Autodesk\\3DSMAX\\11.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  103. ("MAX2010", "SOFTWARE\\Autodesk\\3DSMAX\\12.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  104. ("MAX2011", "SOFTWARE\\Autodesk\\3DSMAX\\13.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  105. ("MAX2012", "SOFTWARE\\Autodesk\\3DSMAX\\14.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  106. ("MAX2013", "SOFTWARE\\Autodesk\\3DSMAX\\15.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  107. ("MAX2014", "SOFTWARE\\Autodesk\\3DSMAX\\16.0\\MAX-1:409", "Installdir", "maxsdk\\include\\CS"),
  108. ]
  109. MAYAVERSIONS = []
  110. MAXVERSIONS = []
  111. DXVERSIONS = ["DX9"]
  112. for (ver,key) in MAYAVERSIONINFO:
  113. MAYAVERSIONS.append(ver)
  114. for (ver,key1,key2,subdir) in MAXVERSIONINFO:
  115. MAXVERSIONS.append(ver)
  116. ########################################################################
  117. ##
  118. ## Potentially Conflicting Files
  119. ##
  120. ## The next function can warn about the existence of files that are
  121. ## commonly generated by ppremake that may conflict with the build.
  122. ##
  123. ########################################################################
  124. CONFLICTING_FILES=["dtool/src/dtoolutil/pandaVersion.h",
  125. "dtool/src/dtoolutil/checkPandaVersion.h",
  126. "dtool/src/dtoolutil/checkPandaVersion.cxx",
  127. "dtool/src/prc/prc_parameters.h",
  128. "panda/src/speedtree/speedtree_parameters.h",
  129. "direct/src/plugin/p3d_plugin_config.h",
  130. "direct/src/plugin_activex/P3DActiveX.rc",
  131. "direct/src/plugin_npapi/nppanda3d.rc",
  132. "direct/src/plugin_standalone/panda3d.rc"]
  133. def WarnConflictingFiles(delete = False):
  134. for cfile in CONFLICTING_FILES:
  135. if os.path.exists(cfile):
  136. print("%sWARNING:%s file may conflict with build: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), cfile, GetColor()))
  137. if delete:
  138. os.unlink(cfile)
  139. print("Deleted.")
  140. ########################################################################
  141. ##
  142. ## The exit routine will normally
  143. ##
  144. ## - print a message
  145. ## - save the dependency cache
  146. ## - exit
  147. ##
  148. ## However, if it is invoked inside a thread, it instead:
  149. ##
  150. ## - prints a message
  151. ## - raises the "initiate-exit" exception
  152. ##
  153. ## If you create a thread, you must be prepared to catch this
  154. ## exception, save the dependency cache, and exit.
  155. ##
  156. ########################################################################
  157. WARNINGS = []
  158. THREADS = {}
  159. HAVE_COLORS = False
  160. SETF = ""
  161. try:
  162. import curses
  163. curses.setupterm()
  164. SETF = curses.tigetstr("setf")
  165. if (SETF == None):
  166. SETF = curses.tigetstr("setaf")
  167. assert SETF != None
  168. HAVE_COLORS = sys.stdout.isatty()
  169. except: pass
  170. def DisableColors():
  171. global HAVE_COLORS
  172. HAVE_COLORS = False
  173. def GetColor(color = None):
  174. if not HAVE_COLORS:
  175. return ""
  176. if color != None:
  177. color = color.lower()
  178. if (color == "blue"):
  179. token = curses.tparm(SETF, 1)
  180. elif (color == "green"):
  181. token = curses.tparm(SETF, 2)
  182. elif (color == "cyan"):
  183. token = curses.tparm(SETF, 3)
  184. elif (color == "red"):
  185. token = curses.tparm(SETF, 4)
  186. elif (color == "magenta"):
  187. token = curses.tparm(SETF, 5)
  188. elif (color == "yellow"):
  189. token = curses.tparm(SETF, 6)
  190. else:
  191. token = curses.tparm(curses.tigetstr("sgr0"))
  192. if sys.version_info >= (3, 0):
  193. return token.decode('ascii')
  194. else:
  195. return token
  196. def ColorText(color, text, reset=True):
  197. if reset is True:
  198. return ''.join((GetColor(color), text, GetColor()))
  199. else:
  200. return ''.join((GetColor(color), text))
  201. def PrettyTime(t):
  202. t = int(t)
  203. hours = t // 3600
  204. t -= hours * 3600
  205. minutes = t // 60
  206. t -= minutes * 60
  207. seconds = t
  208. if hours:
  209. return "%d hours %d min" % (hours, minutes)
  210. if minutes:
  211. return "%d min %d sec" % (minutes, seconds)
  212. return "%d sec" % (seconds)
  213. def ProgressOutput(progress, msg, target = None):
  214. sys.stdout.flush()
  215. sys.stderr.flush()
  216. prefix = ""
  217. thisthread = threading.currentThread()
  218. if thisthread is MAINTHREAD:
  219. if progress is None:
  220. prefix = ""
  221. elif (progress >= 100.0):
  222. prefix = "%s[%s%d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  223. elif (progress < 10.0):
  224. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  225. else:
  226. prefix = "%s[%s %d%%%s] " % (GetColor("yellow"), GetColor("cyan"), progress, GetColor("yellow"))
  227. else:
  228. global THREADS
  229. ident = thread.get_ident()
  230. if (ident not in THREADS):
  231. THREADS[ident] = len(THREADS) + 1
  232. prefix = "%s[%sT%d%s] " % (GetColor("yellow"), GetColor("cyan"), THREADS[ident], GetColor("yellow"))
  233. if target is not None:
  234. suffix = ' ' + ColorText("green", target)
  235. else:
  236. suffix = GetColor()
  237. print(''.join((prefix, msg, suffix)))
  238. sys.stdout.flush()
  239. sys.stderr.flush()
  240. def exit(msg = ""):
  241. sys.stdout.flush()
  242. sys.stderr.flush()
  243. if (threading.currentThread() == MAINTHREAD):
  244. SaveDependencyCache()
  245. print("Elapsed Time: " + PrettyTime(time.time() - STARTTIME))
  246. print(msg)
  247. print(ColorText("red", "Build terminated."))
  248. sys.stdout.flush()
  249. sys.stderr.flush()
  250. ##Don't quit the interperter if I'm running this file directly (debugging)
  251. if __name__ != '__main__':
  252. os._exit(1)
  253. else:
  254. print(msg)
  255. raise "initiate-exit"
  256. ########################################################################
  257. ##
  258. ## SetTarget, GetTarget, GetHost
  259. ##
  260. ## These functions control cross-compilation.
  261. ##
  262. ########################################################################
  263. def GetHost():
  264. """Returns the host platform, ie. the one we're compiling on."""
  265. if sys.platform == 'win32' or sys.platform == 'cygwin':
  266. # sys.platform is win32 on 64-bits Windows as well.
  267. return 'windows'
  268. elif sys.platform == 'darwin':
  269. return 'darwin'
  270. elif sys.platform.startswith('linux'):
  271. try:
  272. # Python seems to offer no built-in way to check this.
  273. osname = subprocess.check_output(["uname", "-o"])
  274. if osname.strip().lower() == b'android':
  275. return 'android'
  276. else:
  277. return 'linux'
  278. except:
  279. return 'linux'
  280. elif sys.platform.startswith('freebsd'):
  281. return 'freebsd'
  282. else:
  283. exit('Unrecognized sys.platform: %s' % (sys.platform))
  284. def GetHostArch():
  285. """Returns the architecture we're compiling on.
  286. Its value is also platform-dependent, as different platforms
  287. have different architecture naming."""
  288. target = GetTarget()
  289. if target == 'windows':
  290. return 'x64' if host_64 else 'x86'
  291. machine = platform.machine()
  292. if machine.startswith('armv7'):
  293. return 'armv7a'
  294. else:
  295. return machine
  296. def SetTarget(target, arch=None):
  297. """Sets the target platform; the one we're compiling for. Also
  298. sets the target architecture (None for default, if any). Should
  299. be called *before* any calls are made to GetOutputDir, GetCC, etc."""
  300. global TARGET, TARGET_ARCH, HAS_TARGET_ARCH
  301. global TOOLCHAIN_PREFIX
  302. host = GetHost()
  303. host_arch = GetHostArch()
  304. if target is None:
  305. target = host
  306. else:
  307. target = target.lower()
  308. if arch is not None:
  309. HAS_TARGET_ARCH = True
  310. TOOLCHAIN_PREFIX = ''
  311. if target == 'windows':
  312. if arch == 'i386':
  313. arch = 'x86'
  314. elif arch == 'amd64':
  315. arch = 'x64'
  316. if arch is not None and arch != 'x86' and arch != 'x64':
  317. exit("Windows architecture must be x86 or x64")
  318. elif target == 'darwin':
  319. if arch == 'amd64':
  320. arch = 'x86_64'
  321. if arch is not None:
  322. choices = ('i386', 'x86_64', 'ppc', 'ppc64')
  323. if arch not in choices:
  324. exit('Mac OS X architecture must be one of %s' % (', '.join(choices)))
  325. elif target == 'android' or target.startswith('android-'):
  326. if arch is None:
  327. # If compiling on Android, default to same architecture. Otherwise, arm.
  328. if host == 'android':
  329. arch = host_arch
  330. else:
  331. arch = 'armv7a'
  332. # Did we specify an API level?
  333. global ANDROID_API
  334. target, _, api = target.partition('-')
  335. if api:
  336. ANDROID_API = int(api)
  337. elif arch in ('mips64', 'aarch64', 'x86_64'):
  338. # 64-bit platforms were introduced in Android 21.
  339. ANDROID_API = 21
  340. else:
  341. # Default to the lowest API level supported by NDK r16.
  342. ANDROID_API = 14
  343. # Determine the prefix for our gcc tools, eg. arm-linux-androideabi-gcc
  344. global ANDROID_ABI, ANDROID_TRIPLE
  345. if arch == 'armv7a':
  346. ANDROID_ABI = 'armeabi-v7a'
  347. ANDROID_TRIPLE = 'arm-linux-androideabi'
  348. elif arch == 'arm':
  349. ANDROID_ABI = 'armeabi'
  350. ANDROID_TRIPLE = 'arm-linux-androideabi'
  351. elif arch == 'aarch64':
  352. ANDROID_ABI = 'arm64-v8a'
  353. ANDROID_TRIPLE = 'aarch64-linux-android'
  354. elif arch == 'mips':
  355. ANDROID_ABI = 'mips'
  356. ANDROID_TRIPLE = 'mipsel-linux-android'
  357. elif arch == 'mips64':
  358. ANDROID_ABI = 'mips64'
  359. ANDROID_TRIPLE = 'mips64el-linux-android'
  360. elif arch == 'x86':
  361. ANDROID_ABI = 'x86'
  362. ANDROID_TRIPLE = 'i686-linux-android'
  363. elif arch == 'x86_64':
  364. ANDROID_ABI = 'x86_64'
  365. ANDROID_TRIPLE = 'x86_64-linux-android'
  366. else:
  367. exit('Android architecture must be arm, armv7a, aarch64, mips, mips64, x86 or x86_64')
  368. TOOLCHAIN_PREFIX = ANDROID_TRIPLE + '-'
  369. elif target == 'linux':
  370. if arch is not None:
  371. TOOLCHAIN_PREFIX = '%s-linux-gnu-' % arch
  372. elif host != 'linux':
  373. exit('Should specify an architecture when building for Linux')
  374. elif target == host:
  375. if arch is None or arch == host_arch:
  376. # Not a cross build.
  377. pass
  378. else:
  379. exit('Cannot cross-compile for %s-%s from %s-%s' % (target, arch, host, host_arch))
  380. else:
  381. exit('Cannot cross-compile for %s from %s' % (target, host))
  382. if arch is None:
  383. arch = host_arch
  384. TARGET = target
  385. TARGET_ARCH = arch
  386. def GetTarget():
  387. """Returns the platform we're compiling for. Defaults to GetHost()."""
  388. global TARGET
  389. if TARGET is None:
  390. TARGET = GetHost()
  391. return TARGET
  392. def HasTargetArch():
  393. """Returns True if the user specified an architecture to compile for."""
  394. return HAS_TARGET_ARCH
  395. def GetTargetArch():
  396. """Returns the architecture we're compiling for. Defaults to GetHostArch().
  397. Its value is also dependent on that of GetTarget(), as different platforms
  398. use a different architecture naming."""
  399. global TARGET_ARCH
  400. if TARGET_ARCH is None:
  401. TARGET_ARCH = GetHostArch()
  402. return TARGET_ARCH
  403. def CrossCompiling():
  404. """Returns True if we're cross-compiling."""
  405. return GetTarget() != GetHost()
  406. def GetCC():
  407. if TARGET in ('darwin', 'freebsd', 'android'):
  408. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'clang')
  409. else:
  410. return os.environ.get('CC', TOOLCHAIN_PREFIX + 'gcc')
  411. def GetCXX():
  412. if TARGET in ('darwin', 'freebsd', 'android'):
  413. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'clang++')
  414. else:
  415. return os.environ.get('CXX', TOOLCHAIN_PREFIX + 'g++')
  416. def GetStrip():
  417. # Hack
  418. if TARGET == 'android':
  419. return TOOLCHAIN_PREFIX + 'strip'
  420. else:
  421. return 'strip'
  422. def GetAR():
  423. # Hack
  424. if TARGET == 'android':
  425. return TOOLCHAIN_PREFIX + 'ar'
  426. else:
  427. return 'ar'
  428. def GetRanlib():
  429. # Hack
  430. if TARGET == 'android':
  431. return TOOLCHAIN_PREFIX + 'ranlib'
  432. else:
  433. return 'ranlib'
  434. BISON = None
  435. def GetBison():
  436. global BISON
  437. if BISON is not None:
  438. return BISON
  439. # We now require a newer version of Bison than the one we previously
  440. # shipped in the win-util dir. The new version has a 'data'
  441. # subdirectory, so check for that.
  442. win_util_data = os.path.join(GetThirdpartyBase(), 'win-util', 'data')
  443. if GetHost() == 'windows' and os.path.isdir(win_util_data):
  444. BISON = os.path.join(GetThirdpartyBase(), 'win-util', 'bison.exe')
  445. elif LocateBinary('bison'):
  446. BISON = 'bison'
  447. else:
  448. # We don't strictly need it, so don't give an error
  449. return None
  450. return BISON
  451. FLEX = None
  452. def GetFlex():
  453. global FLEX
  454. if FLEX is not None:
  455. return FLEX
  456. win_util = os.path.join(GetThirdpartyBase(), 'win-util')
  457. if GetHost() == 'windows' and os.path.isdir(win_util):
  458. FLEX = GetThirdpartyBase() + "/win-util/flex.exe"
  459. elif LocateBinary('flex'):
  460. FLEX = 'flex'
  461. else:
  462. # We don't strictly need it, so don't give an error
  463. return None
  464. return FLEX
  465. ########################################################################
  466. ##
  467. ## LocateBinary
  468. ##
  469. ## This function searches the system PATH for the binary. Returns its
  470. ## full path when it is found, or None when it was not found.
  471. ##
  472. ########################################################################
  473. def LocateBinary(binary):
  474. if os.path.isfile(binary):
  475. return binary
  476. if "PATH" not in os.environ or os.environ["PATH"] == "":
  477. p = os.defpath
  478. else:
  479. p = os.environ["PATH"]
  480. pathList = p.split(os.pathsep)
  481. if GetHost() == 'windows':
  482. if not binary.endswith('.exe'):
  483. # Append .exe if necessary
  484. binary += '.exe'
  485. # On Windows the current directory is always implicitly
  486. # searched before anything else on PATH.
  487. pathList = ['.'] + pathList
  488. for path in pathList:
  489. binpath = os.path.join(os.path.expanduser(path), binary)
  490. if os.access(binpath, os.X_OK):
  491. return os.path.abspath(os.path.realpath(binpath))
  492. return None
  493. ########################################################################
  494. ##
  495. ## Run a command.
  496. ##
  497. ########################################################################
  498. def oscmd(cmd, ignoreError = False):
  499. if VERBOSE:
  500. print(GetColor("blue") + cmd.split(" ", 1)[0] + " " + GetColor("magenta") + cmd.split(" ", 1)[1] + GetColor())
  501. sys.stdout.flush()
  502. if sys.platform == "win32":
  503. exe = cmd.split()[0]
  504. exe_path = LocateBinary(exe)
  505. if exe_path is None:
  506. exit("Cannot find "+exe+" on search path")
  507. res = os.spawnl(os.P_WAIT, exe_path, cmd)
  508. else:
  509. cmd = cmd.replace(';', '\\;')
  510. res = subprocess.call(cmd, shell=True)
  511. sig = res & 0x7F
  512. if (GetVerbose() and res != 0):
  513. print(ColorText("red", "Process exited with exit status %d and signal code %d" % ((res & 0xFF00) >> 8, sig)))
  514. if (sig == signal.SIGINT):
  515. exit("keyboard interrupt")
  516. # Don't ask me where the 35584 or 34304 come from...
  517. if (sig == signal.SIGSEGV or res == 35584 or res == 34304):
  518. if (LocateBinary("gdb") and GetVerbose() and GetHost() != "windows"):
  519. print(ColorText("red", "Received SIGSEGV, retrieving traceback..."))
  520. os.system("gdb -batch -ex 'handle SIG33 pass nostop noprint' -ex 'set pagination 0' -ex 'run' -ex 'bt full' -ex 'info registers' -ex 'thread apply all backtrace' -ex 'quit' --args %s < /dev/null" % cmd)
  521. else:
  522. print(ColorText("red", "Received SIGSEGV"))
  523. exit("")
  524. if res != 0 and not ignoreError:
  525. if "interrogate" in cmd.split(" ", 1)[0] and GetVerbose():
  526. print(ColorText("red", "Interrogate failed, retrieving debug output..."))
  527. sys.stdout.flush()
  528. verbose_cmd = cmd.split(" ", 1)[0] + " -vv " + cmd.split(" ", 1)[1]
  529. if sys.platform == "win32":
  530. os.spawnl(os.P_WAIT, exe_path, verbose_cmd)
  531. else:
  532. subprocess.call(verbose_cmd, shell=True)
  533. exit("The following command returned a non-zero value: " + str(cmd))
  534. return res
  535. ########################################################################
  536. ##
  537. ## GetDirectoryContents
  538. ##
  539. ########################################################################
  540. def GetDirectoryContents(dir, filters="*", skip=[]):
  541. if (type(filters)==str):
  542. filters = [filters]
  543. actual = {}
  544. files = os.listdir(dir)
  545. for filter in filters:
  546. for file in fnmatch.filter(files, filter):
  547. if (skip.count(file)==0) and (os.path.isfile(dir + "/" + file)):
  548. actual[file] = 1
  549. results = list(actual.keys())
  550. results.sort()
  551. return results
  552. def GetDirectorySize(dir):
  553. if not os.path.isdir(dir):
  554. return 0
  555. size = 0
  556. for (path, dirs, files) in os.walk(dir):
  557. for file in files:
  558. try:
  559. size += os.path.getsize(os.path.join(path, file))
  560. except: pass
  561. return size
  562. ########################################################################
  563. ##
  564. ## The Timestamp Cache
  565. ##
  566. ## The make utility is constantly fetching the timestamps of files.
  567. ## This can represent the bulk of the file accesses during the make
  568. ## process. The timestamp cache eliminates redundant checks.
  569. ##
  570. ########################################################################
  571. TIMESTAMPCACHE = {}
  572. def GetTimestamp(path):
  573. if path in TIMESTAMPCACHE:
  574. return TIMESTAMPCACHE[path]
  575. try: date = os.path.getmtime(path)
  576. except: date = 0
  577. TIMESTAMPCACHE[path] = date
  578. return date
  579. def ClearTimestamp(path):
  580. del TIMESTAMPCACHE[path]
  581. ########################################################################
  582. ##
  583. ## The Dependency cache.
  584. ##
  585. ## Makepanda's strategy for file dependencies is different from most
  586. ## make-utilities. Whenever a file is built, makepanda records
  587. ## that the file was built, and it records what the input files were,
  588. ## and what their dates were. Whenever a file is about to be built,
  589. ## panda compares the current list of input files and their dates,
  590. ## to the previous list of input files and their dates. If they match,
  591. ## there is no need to build the file.
  592. ##
  593. ########################################################################
  594. BUILTFROMCACHE = {}
  595. def JustBuilt(files, others):
  596. dates = {}
  597. for file in files:
  598. del TIMESTAMPCACHE[file]
  599. dates[file] = GetTimestamp(file)
  600. for file in others:
  601. dates[file] = GetTimestamp(file)
  602. key = tuple(files)
  603. BUILTFROMCACHE[key] = dates
  604. def NeedsBuild(files, others):
  605. dates = {}
  606. for file in files:
  607. dates[file] = GetTimestamp(file)
  608. if not os.path.exists(file):
  609. if DEBUG_DEPENDENCIES:
  610. print("rebuilding %s because it does not exist" % (file))
  611. return True
  612. for file in others:
  613. dates[file] = GetTimestamp(file)
  614. key = tuple(files)
  615. if key in BUILTFROMCACHE:
  616. cached = BUILTFROMCACHE[key]
  617. if cached == dates:
  618. return False
  619. elif DEBUG_DEPENDENCIES:
  620. print("rebuilding %s because:" % (key))
  621. for key in frozenset(cached.keys()) | frozenset(dates.keys()):
  622. if key not in cached:
  623. print(" new dependency: %s" % (key))
  624. elif key not in dates:
  625. print(" removed dependency: %s" % (key))
  626. elif cached[key] != dates[key]:
  627. print(" dependency changed: %s" % (key))
  628. if VERBOSE and frozenset(cached) != frozenset(dates):
  629. print("%sWARNING:%s file dependencies changed: %s%s%s" % (GetColor("red"), GetColor(), GetColor("green"), files, GetColor()))
  630. return True
  631. ########################################################################
  632. ##
  633. ## The CXX include cache:
  634. ##
  635. ## The following routine scans a CXX file and returns a list of
  636. ## the include-directives inside that file. It's not recursive:
  637. ## it just returns the includes that are textually inside the
  638. ## file. If you need recursive dependencies, you need the higher-level
  639. ## routine CxxCalcDependencies, defined elsewhere.
  640. ##
  641. ## Since scanning a CXX file is slow, we cache the result. It records
  642. ## the date of the source file and the list of includes that it
  643. ## contains. It assumes that if the file date hasn't changed, that
  644. ## the list of include-statements inside the file has not changed
  645. ## either. Once again, this particular routine does not return
  646. ## recursive dependencies --- it only returns an explicit list of
  647. ## include statements that are textually inside the file. That
  648. ## is what the cache stores, as well.
  649. ##
  650. ########################################################################
  651. CXXINCLUDECACHE = {}
  652. global CxxIncludeRegex
  653. CxxIncludeRegex = re.compile('^[ \t]*[#][ \t]*include[ \t]+"([^"]+)"[ \t\r\n]*$')
  654. def CxxGetIncludes(path):
  655. date = GetTimestamp(path)
  656. if (path in CXXINCLUDECACHE):
  657. cached = CXXINCLUDECACHE[path]
  658. if (cached[0]==date): return cached[1]
  659. try: sfile = open(path, 'r')
  660. except:
  661. exit("Cannot open source file \""+path+"\" for reading.")
  662. include = []
  663. try:
  664. for line in sfile:
  665. match = CxxIncludeRegex.match(line,0)
  666. if (match):
  667. incname = match.group(1)
  668. include.append(incname)
  669. except:
  670. print("Failed to determine dependencies of \""+path+"\".")
  671. raise
  672. sfile.close()
  673. CXXINCLUDECACHE[path] = [date, include]
  674. return include
  675. JAVAIMPORTCACHE = {}
  676. global JavaImportRegex
  677. JavaImportRegex = re.compile('[ \t\r\n;]import[ \t]+([a-zA-Z][^;]+)[ \t\r\n]*;')
  678. def JavaGetImports(path):
  679. date = GetTimestamp(path)
  680. if path in JAVAIMPORTCACHE:
  681. cached = JAVAIMPORTCACHE[path]
  682. if cached[0] == date:
  683. return cached[1]
  684. try:
  685. source = open(path, 'r').read()
  686. except:
  687. exit("Cannot open source file \"" + path + "\" for reading.")
  688. imports = []
  689. try:
  690. for match in JavaImportRegex.finditer(source, 0):
  691. impname = match.group(1)
  692. imports.append(impname.strip())
  693. except:
  694. print("Failed to determine dependencies of \"" + path +"\".")
  695. raise
  696. JAVAIMPORTCACHE[path] = [date, imports]
  697. return imports
  698. ########################################################################
  699. ##
  700. ## SaveDependencyCache / LoadDependencyCache
  701. ##
  702. ## This actually saves both the dependency and cxx-include caches.
  703. ##
  704. ########################################################################
  705. DCACHE_VERSION = 2
  706. DCACHE_BACKED_UP = False
  707. def SaveDependencyCache():
  708. global DCACHE_BACKED_UP
  709. if not DCACHE_BACKED_UP:
  710. try:
  711. if (os.path.exists(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"))):
  712. os.rename(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),
  713. os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache-backup"))
  714. except: pass
  715. DCACHE_BACKED_UP = True
  716. try:
  717. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"),'wb')
  718. except:
  719. icache = None
  720. if icache is not None:
  721. print("Storing dependency cache.")
  722. pickle.dump(DCACHE_VERSION, icache, 0)
  723. pickle.dump(CXXINCLUDECACHE, icache, 2)
  724. pickle.dump(BUILTFROMCACHE, icache, 2)
  725. icache.close()
  726. def LoadDependencyCache():
  727. global CXXINCLUDECACHE
  728. global BUILTFROMCACHE
  729. try:
  730. icache = open(os.path.join(OUTPUTDIR, "tmp", "makepanda-dcache"), 'rb')
  731. except:
  732. icache = None
  733. if icache is not None:
  734. ver = pickle.load(icache)
  735. if ver == DCACHE_VERSION:
  736. CXXINCLUDECACHE = pickle.load(icache)
  737. BUILTFROMCACHE = pickle.load(icache)
  738. icache.close()
  739. else:
  740. print("Cannot load dependency cache, version is too old!")
  741. ########################################################################
  742. ##
  743. ## CxxFindSource: given a source file name and a directory list,
  744. ## searches the directory list for the given source file. Returns
  745. ## the full pathname of the located file.
  746. ##
  747. ## CxxFindHeader: given a source file, an include directive, and a
  748. ## directory list, searches the directory list for the given header
  749. ## file. Returns the full pathname of the located file.
  750. ##
  751. ## Of course, CxxFindSource and CxxFindHeader cannot find a source
  752. ## file that has not been created yet. This can cause dependency
  753. ## problems. So the function CreateStubHeader can be used to create
  754. ## a file that CxxFindSource or CxxFindHeader can subsequently find.
  755. ##
  756. ########################################################################
  757. def CxxFindSource(name, ipath):
  758. for dir in ipath:
  759. if (dir == "."): full = name
  760. else: full = dir + "/" + name
  761. if GetTimestamp(full) > 0: return full
  762. exit("Could not find source file: "+name)
  763. def CxxFindHeader(srcfile, incfile, ipath):
  764. if (incfile.startswith(".")):
  765. last = srcfile.rfind("/")
  766. if (last < 0): exit("CxxFindHeader cannot handle this case #1")
  767. srcdir = srcfile[:last+1]
  768. while (incfile[:1]=="."):
  769. if (incfile[:2]=="./"):
  770. incfile = incfile[2:]
  771. elif (incfile[:3]=="../"):
  772. incfile = incfile[3:]
  773. last = srcdir[:-1].rfind("/")
  774. if (last < 0): exit("CxxFindHeader cannot handle this case #2")
  775. srcdir = srcdir[:last+1]
  776. else: exit("CxxFindHeader cannot handle this case #3")
  777. full = srcdir + incfile
  778. if GetTimestamp(full) > 0: return full
  779. return 0
  780. else:
  781. for dir in ipath:
  782. full = dir + "/" + incfile
  783. if GetTimestamp(full) > 0: return full
  784. return 0
  785. def JavaFindClasses(impspec, clspath):
  786. path = clspath + '/' + impspec.replace('.', '/') + '.class'
  787. if '*' in path:
  788. return glob.glob(path)
  789. else:
  790. return [path]
  791. ########################################################################
  792. ##
  793. ## CxxCalcDependencies(srcfile, ipath, ignore)
  794. ##
  795. ## Calculate the dependencies of a source file given a
  796. ## particular include-path. Any file in the list of files to
  797. ## ignore is not considered.
  798. ##
  799. ########################################################################
  800. global CxxIgnoreHeader
  801. global CxxDependencyCache
  802. CxxIgnoreHeader = {}
  803. CxxDependencyCache = {}
  804. def CxxCalcDependencies(srcfile, ipath, ignore):
  805. if (srcfile in CxxDependencyCache):
  806. return CxxDependencyCache[srcfile]
  807. if (ignore.count(srcfile)): return []
  808. dep = {}
  809. dep[srcfile] = 1
  810. includes = CxxGetIncludes(srcfile)
  811. for include in includes:
  812. header = CxxFindHeader(srcfile, include, ipath)
  813. if (header!=0):
  814. if (ignore.count(header)==0):
  815. hdeps = CxxCalcDependencies(header, ipath, [srcfile]+ignore)
  816. for x in hdeps: dep[x] = 1
  817. result = list(dep.keys())
  818. CxxDependencyCache[srcfile] = result
  819. return result
  820. global JavaDependencyCache
  821. JavaDependencyCache = {}
  822. def JavaCalcDependencies(srcfile, clspath):
  823. if srcfile in JavaDependencyCache:
  824. return JavaDependencyCache[srcfile]
  825. deps = set((srcfile,))
  826. JavaDependencyCache[srcfile] = deps
  827. imports = JavaGetImports(srcfile)
  828. for impspec in imports:
  829. for cls in JavaFindClasses(impspec, clspath):
  830. deps.add(cls)
  831. return deps
  832. ########################################################################
  833. ##
  834. ## Registry Key Handling
  835. ##
  836. ## Of course, these routines will fail if you call them on a
  837. ## non win32 platform. If you use them on a win64 platform, they
  838. ## will look in the win32 private hive first, then look in the
  839. ## win64 hive.
  840. ##
  841. ########################################################################
  842. if sys.platform == "win32":
  843. # Note: not supported on cygwin.
  844. if sys.version_info >= (3, 0):
  845. import winreg
  846. else:
  847. import _winreg as winreg
  848. def TryRegistryKey(path):
  849. try:
  850. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ)
  851. return key
  852. except: pass
  853. try:
  854. key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_READ | 256)
  855. return key
  856. except: pass
  857. return 0
  858. def ListRegistryKeys(path):
  859. result=[]
  860. index=0
  861. key = TryRegistryKey(path)
  862. if (key != 0):
  863. try:
  864. while (1):
  865. result.append(winreg.EnumKey(key, index))
  866. index = index + 1
  867. except: pass
  868. winreg.CloseKey(key)
  869. return result
  870. def ListRegistryValues(path):
  871. result = []
  872. index = 0
  873. key = TryRegistryKey(path)
  874. if (key != 0):
  875. try:
  876. while (1):
  877. result.append(winreg.EnumValue(key, index)[0])
  878. index = index + 1
  879. except: pass
  880. winreg.CloseKey(key)
  881. return result
  882. def GetRegistryKey(path, subkey, override64=True):
  883. if (host_64 and override64):
  884. path = path.replace("SOFTWARE\\", "SOFTWARE\\Wow6432Node\\")
  885. k1=0
  886. key = TryRegistryKey(path)
  887. if (key != 0):
  888. try:
  889. k1, k2 = winreg.QueryValueEx(key, subkey)
  890. except: pass
  891. winreg.CloseKey(key)
  892. return k1
  893. def GetProgramFiles():
  894. if ("PROGRAMFILES" in os.environ):
  895. return os.environ["PROGRAMFILES"]
  896. elif (os.path.isdir("C:\\Program Files")):
  897. return "C:\\Program Files"
  898. elif (os.path.isdir("D:\\Program Files")):
  899. return "D:\\Program Files"
  900. elif (os.path.isdir("E:\\Program Files")):
  901. return "E:\\Program Files"
  902. return 0
  903. def GetProgramFiles_x86():
  904. if ("ProgramFiles(x86)" in os.environ):
  905. return os.environ["ProgramFiles(x86)"]
  906. elif (os.path.isdir("C:\\Program Files (x86)")):
  907. return "C:\\Program Files (x86)"
  908. elif (os.path.isdir("D:\\Program Files (x86)")):
  909. return "D:\\Program Files (x86)"
  910. elif (os.path.isdir("E:\\Program Files (x86)")):
  911. return "E:\\Program Files (x86)"
  912. return GetProgramFiles()
  913. ########################################################################
  914. ##
  915. ## Parsing Compiler Option Lists
  916. ##
  917. ########################################################################
  918. def GetListOption(opts, prefix):
  919. res=[]
  920. for x in opts:
  921. if (x.startswith(prefix)):
  922. res.append(x[len(prefix):])
  923. return res
  924. def GetValueOption(opts, prefix):
  925. for x in opts:
  926. if (x.startswith(prefix)):
  927. return x[len(prefix):]
  928. return 0
  929. def GetOptimizeOption(opts):
  930. val = GetValueOption(opts, "OPT:")
  931. if (val == 0):
  932. return OPTIMIZE
  933. return val
  934. ########################################################################
  935. ##
  936. ## General File Manipulation
  937. ##
  938. ########################################################################
  939. def MakeDirectory(path):
  940. if os.path.isdir(path): return 0
  941. os.mkdir(path)
  942. def ReadFile(wfile):
  943. try:
  944. srchandle = open(wfile, "r")
  945. data = srchandle.read()
  946. srchandle.close()
  947. return data
  948. except:
  949. ex = sys.exc_info()[1]
  950. exit("Cannot read %s: %s" % (wfile, ex))
  951. def ReadBinaryFile(wfile):
  952. try:
  953. srchandle = open(wfile, "rb")
  954. data = srchandle.read()
  955. srchandle.close()
  956. return data
  957. except:
  958. ex = sys.exc_info()[1]
  959. exit("Cannot read %s: %s" % (wfile, ex))
  960. def WriteFile(wfile, data, newline=None):
  961. if newline is not None:
  962. data = data.replace('\r\n', '\n')
  963. data = data.replace('\r', '\n')
  964. data = data.replace('\n', newline)
  965. try:
  966. if sys.version_info >= (3, 0):
  967. dsthandle = open(wfile, "w", newline='')
  968. else:
  969. dsthandle = open(wfile, "w")
  970. dsthandle.write(data)
  971. dsthandle.close()
  972. except:
  973. ex = sys.exc_info()[1]
  974. exit("Cannot write to %s: %s" % (wfile, ex))
  975. def WriteBinaryFile(wfile, data):
  976. try:
  977. dsthandle = open(wfile, "wb")
  978. dsthandle.write(data)
  979. dsthandle.close()
  980. except:
  981. ex = sys.exc_info()[1]
  982. exit("Cannot write to %s: %s" % (wfile, ex))
  983. def ConditionalWriteFile(dest, data, newline=None):
  984. if newline is not None:
  985. data = data.replace('\r\n', '\n')
  986. data = data.replace('\r', '\n')
  987. data = data.replace('\n', newline)
  988. try:
  989. rfile = open(dest, 'r')
  990. contents = rfile.read(-1)
  991. rfile.close()
  992. except:
  993. contents = 0
  994. if contents != data:
  995. if VERBOSE:
  996. print("Writing %s" % (dest))
  997. sys.stdout.flush()
  998. WriteFile(dest, data)
  999. def DeleteVCS(dir):
  1000. if dir == "": dir = "."
  1001. for entry in os.listdir(dir):
  1002. subdir = os.path.join(dir, entry)
  1003. if (os.path.isdir(subdir)):
  1004. if entry in VCS_DIRS:
  1005. shutil.rmtree(subdir)
  1006. else:
  1007. DeleteVCS(subdir)
  1008. elif (os.path.isfile(subdir) and (entry in VCS_FILES or entry.startswith(".#"))):
  1009. os.remove(subdir)
  1010. def DeleteBuildFiles(dir):
  1011. if dir == "": dir = "."
  1012. for entry in os.listdir(dir):
  1013. subdir = os.path.join(dir, entry)
  1014. if (os.path.isfile(subdir) and os.path.splitext(subdir)[-1] in [".pp", ".moved"]):
  1015. os.remove(subdir)
  1016. elif (os.path.isdir(subdir)):
  1017. if (os.path.basename(subdir)[:3] == "Opt" and os.path.basename(subdir)[4] == "-"):
  1018. shutil.rmtree(subdir)
  1019. else:
  1020. DeleteBuildFiles(subdir)
  1021. def DeleteEmptyDirs(dir):
  1022. if dir == "": dir = "."
  1023. entries = os.listdir(dir)
  1024. if not entries:
  1025. os.rmdir(dir)
  1026. return
  1027. for entry in entries:
  1028. subdir = os.path.join(dir, entry)
  1029. if (os.path.isdir(subdir)):
  1030. if (not os.listdir(subdir)):
  1031. os.rmdir(subdir)
  1032. else:
  1033. DeleteEmptyDirs(subdir)
  1034. def CreateFile(file):
  1035. if (os.path.exists(file)==0):
  1036. WriteFile(file, "")
  1037. ########################################################################
  1038. #
  1039. # Create the panda build tree.
  1040. #
  1041. ########################################################################
  1042. def MakeBuildTree():
  1043. MakeDirectory(OUTPUTDIR)
  1044. MakeDirectory(OUTPUTDIR + "/bin")
  1045. MakeDirectory(OUTPUTDIR + "/lib")
  1046. MakeDirectory(OUTPUTDIR + "/tmp")
  1047. MakeDirectory(OUTPUTDIR + "/etc")
  1048. MakeDirectory(OUTPUTDIR + "/plugins")
  1049. MakeDirectory(OUTPUTDIR + "/include")
  1050. MakeDirectory(OUTPUTDIR + "/models")
  1051. MakeDirectory(OUTPUTDIR + "/models/audio")
  1052. MakeDirectory(OUTPUTDIR + "/models/audio/sfx")
  1053. MakeDirectory(OUTPUTDIR + "/models/icons")
  1054. MakeDirectory(OUTPUTDIR + "/models/maps")
  1055. MakeDirectory(OUTPUTDIR + "/models/misc")
  1056. MakeDirectory(OUTPUTDIR + "/models/gui")
  1057. MakeDirectory(OUTPUTDIR + "/pandac")
  1058. MakeDirectory(OUTPUTDIR + "/pandac/input")
  1059. MakeDirectory(OUTPUTDIR + "/panda3d")
  1060. if GetTarget() == 'darwin':
  1061. MakeDirectory(OUTPUTDIR + "/Frameworks")
  1062. elif GetTarget() == 'android':
  1063. MakeDirectory(OUTPUTDIR + "/classes")
  1064. ########################################################################
  1065. #
  1066. # Make sure that you are in the root of the panda tree.
  1067. #
  1068. ########################################################################
  1069. def CheckPandaSourceTree():
  1070. dir = os.getcwd()
  1071. if ((os.path.exists(os.path.join(dir, "makepanda/makepanda.py"))==0) or
  1072. (os.path.exists(os.path.join(dir, "dtool", "src", "dtoolbase", "dtoolbase.h"))==0) or
  1073. (os.path.exists(os.path.join(dir, "panda", "src", "pandabase", "pandabase.h"))==0)):
  1074. exit("Current directory is not the root of the panda tree.")
  1075. ########################################################################
  1076. ##
  1077. ## Thirdparty libraries paths
  1078. ##
  1079. ########################################################################
  1080. def GetThirdpartyBase():
  1081. """Returns the location of the 'thirdparty' directory.
  1082. Normally, this is simply the thirdparty directory relative
  1083. to the root of the source root, but if a MAKEPANDA_THIRDPARTY
  1084. environment variable was set, it is used as the location of the
  1085. thirdparty directory. This is useful when wanting to use a single
  1086. system-wide thirdparty directory, for instance on a build machine."""
  1087. global THIRDPARTYBASE
  1088. if (THIRDPARTYBASE != None):
  1089. return THIRDPARTYBASE
  1090. THIRDPARTYBASE = "thirdparty"
  1091. if "MAKEPANDA_THIRDPARTY" in os.environ:
  1092. THIRDPARTYBASE = os.environ["MAKEPANDA_THIRDPARTY"]
  1093. return THIRDPARTYBASE
  1094. def GetThirdpartyDir():
  1095. """Returns the thirdparty directory for the target platform,
  1096. ie. thirdparty/win-libs-vc10/. May return None in the future."""
  1097. global THIRDPARTYDIR
  1098. if THIRDPARTYDIR != None:
  1099. return THIRDPARTYDIR
  1100. base = GetThirdpartyBase()
  1101. target = GetTarget()
  1102. target_arch = GetTargetArch()
  1103. if (target == 'windows'):
  1104. vc = str(SDK["MSVC_VERSION"][0])
  1105. if target_arch == 'x64':
  1106. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "-x64/"
  1107. else:
  1108. THIRDPARTYDIR = base + "/win-libs-vc" + vc + "/"
  1109. elif (target == 'darwin'):
  1110. # OSX thirdparty binaries are universal, where possible.
  1111. THIRDPARTYDIR = base + "/darwin-libs-a/"
  1112. elif (target == 'linux'):
  1113. if (target_arch.startswith("arm")):
  1114. THIRDPARTYDIR = base + "/linux-libs-arm/"
  1115. elif (target_arch in ("x86_64", "amd64")):
  1116. THIRDPARTYDIR = base + "/linux-libs-x64/"
  1117. else:
  1118. THIRDPARTYDIR = base + "/linux-libs-a/"
  1119. elif (target == 'freebsd'):
  1120. if (target_arch.startswith("arm")):
  1121. THIRDPARTYDIR = base + "/freebsd-libs-arm/"
  1122. elif (target_arch in ("x86_64", "amd64")):
  1123. THIRDPARTYDIR = base + "/freebsd-libs-x64/"
  1124. else:
  1125. THIRDPARTYDIR = base + "/freebsd-libs-a/"
  1126. elif (target == 'android'):
  1127. THIRDPARTYDIR = GetThirdpartyBase()+"/android-libs-%s/" % (GetTargetArch())
  1128. else:
  1129. print("%s Unsupported platform: %s" % (ColorText("red", "WARNING:"), target))
  1130. return
  1131. if (GetVerbose()):
  1132. print("Using thirdparty directory: %s" % THIRDPARTYDIR)
  1133. return THIRDPARTYDIR
  1134. ########################################################################
  1135. ##
  1136. ## Gets or sets the output directory, by default "built".
  1137. ## Gets or sets the optimize level.
  1138. ## Gets or sets the verbose flag.
  1139. ##
  1140. ########################################################################
  1141. def GetOutputDir():
  1142. return OUTPUTDIR
  1143. def IsCustomOutputDir():
  1144. return CUSTOM_OUTPUTDIR
  1145. def SetOutputDir(outputdir):
  1146. global OUTPUTDIR, CUSTOM_OUTPUTDIR
  1147. OUTPUTDIR = outputdir
  1148. CUSTOM_OUTPUTDIR = True
  1149. def GetOptimize():
  1150. return int(OPTIMIZE)
  1151. def SetOptimize(optimize):
  1152. global OPTIMIZE
  1153. OPTIMIZE = optimize
  1154. def GetVerbose():
  1155. return VERBOSE
  1156. def SetVerbose(verbose):
  1157. global VERBOSE
  1158. VERBOSE = verbose
  1159. def SetDebugDependencies(dd = True):
  1160. global DEBUG_DEPENDENCIES
  1161. DEBUG_DEPENDENCIES = dd
  1162. def GetLinkAllStatic():
  1163. return LINK_ALL_STATIC
  1164. def SetLinkAllStatic(val = True):
  1165. global LINK_ALL_STATIC
  1166. LINK_ALL_STATIC = val
  1167. def UnsetLinkAllStatic():
  1168. global LINK_ALL_STATIC
  1169. LINK_ALL_STATIC = False
  1170. ########################################################################
  1171. ##
  1172. ## Package Selection
  1173. ##
  1174. ## This facility enables makepanda to keep a list of packages selected
  1175. ## by the user for inclusion or omission.
  1176. ##
  1177. ########################################################################
  1178. PKG_LIST_ALL = []
  1179. PKG_LIST_OMIT = {}
  1180. PKG_LIST_CUSTOM = set()
  1181. def PkgListSet(pkgs):
  1182. global PKG_LIST_ALL
  1183. global PKG_LIST_OMIT
  1184. PKG_LIST_ALL=pkgs
  1185. PKG_LIST_OMIT={}
  1186. PkgEnableAll()
  1187. def PkgListGet():
  1188. return PKG_LIST_ALL
  1189. def PkgEnableAll():
  1190. for x in PKG_LIST_ALL:
  1191. PKG_LIST_OMIT[x] = 0
  1192. def PkgDisableAll():
  1193. for x in PKG_LIST_ALL:
  1194. PKG_LIST_OMIT[x] = 1
  1195. def PkgEnable(pkg):
  1196. PKG_LIST_OMIT[pkg] = 0
  1197. def PkgDisable(pkg):
  1198. PKG_LIST_OMIT[pkg] = 1
  1199. def PkgSetCustomLocation(pkg):
  1200. PKG_LIST_CUSTOM.add(pkg)
  1201. def PkgHasCustomLocation(pkg):
  1202. return pkg in PKG_LIST_CUSTOM
  1203. def PkgSkip(pkg):
  1204. return PKG_LIST_OMIT[pkg]
  1205. def PkgSelected(pkglist, pkg):
  1206. if (pkglist.count(pkg)==0): return 0
  1207. if (PKG_LIST_OMIT[pkg]): return 0
  1208. return 1
  1209. ########################################################################
  1210. ##
  1211. ## DTOOL/PRC Option value override
  1212. ##
  1213. ## This facility enables makepanda to keep a list of parameters
  1214. ## overriden by the command line.
  1215. ##
  1216. ########################################################################
  1217. OVERRIDES_LIST={}
  1218. def AddOverride(spec):
  1219. if (spec.find("=")==-1):return
  1220. pair = spec.split("=",1)
  1221. OVERRIDES_LIST[pair[0]] = pair[1]
  1222. def OverrideValue(parameter, value):
  1223. if parameter in OVERRIDES_LIST:
  1224. print("Overriding value of key \"" + parameter + "\" with value \"" + OVERRIDES_LIST[parameter] + "\"")
  1225. return OVERRIDES_LIST[parameter]
  1226. else:
  1227. return value
  1228. ########################################################################
  1229. ##
  1230. ## These functions are for libraries which use pkg-config.
  1231. ##
  1232. ########################################################################
  1233. def PkgConfigHavePkg(pkgname, tool = "pkg-config"):
  1234. """Returns a bool whether the pkg-config package is installed."""
  1235. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1236. return False
  1237. if (tool == "pkg-config"):
  1238. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --modversion " + pkgname)
  1239. else:
  1240. return bool(LocateBinary(tool) != None)
  1241. result = handle.read().strip()
  1242. returnval = handle.close()
  1243. if returnval != None and returnval != 0:
  1244. return False
  1245. return bool(len(result) > 0)
  1246. def PkgConfigGetLibs(pkgname, tool = "pkg-config"):
  1247. """Returns a list of libs for the package, prefixed by -l."""
  1248. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1249. return []
  1250. if (tool == "pkg-config"):
  1251. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-l " + pkgname)
  1252. elif (tool == "fltk-config"):
  1253. handle = os.popen(LocateBinary("fltk-config") + " --ldstaticflags")
  1254. else:
  1255. handle = os.popen(LocateBinary(tool) + " --libs")
  1256. result = handle.read().strip()
  1257. handle.close()
  1258. libs = []
  1259. # Walk through the result arguments carefully. Look for -lname as
  1260. # well as -framework name.
  1261. r = result.split(' ')
  1262. ri = 0
  1263. while ri < len(r):
  1264. l = r[ri]
  1265. if l.startswith("-l") or l.startswith("/"):
  1266. libs.append(l)
  1267. elif l == '-framework':
  1268. libs.append(l)
  1269. ri += 1
  1270. libs.append(r[ri])
  1271. ri += 1
  1272. return libs
  1273. def PkgConfigGetIncDirs(pkgname, tool = "pkg-config"):
  1274. """Returns a list of includes for the package, NOT prefixed by -I."""
  1275. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1276. return []
  1277. if (tool == "pkg-config"):
  1278. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags-only-I " + pkgname)
  1279. else:
  1280. handle = os.popen(LocateBinary(tool) + " --cflags")
  1281. result = handle.read().strip()
  1282. if len(result) == 0: return []
  1283. handle.close()
  1284. dirs = []
  1285. for opt in result.split(" "):
  1286. if (opt.startswith("-I")):
  1287. inc_dir = opt.replace("-I", "").replace("\"", "").strip()
  1288. # Hack for ODE, otherwise -S/usr/include gets added to interrogate
  1289. if inc_dir != '/usr/include' and inc_dir != '/usr/include/':
  1290. dirs.append(inc_dir)
  1291. return dirs
  1292. def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"):
  1293. """Returns a list of library paths for the package, NOT prefixed by -L."""
  1294. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1295. return []
  1296. if (tool == "pkg-config"):
  1297. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname)
  1298. elif (tool == "wx-config" or tool == "ode-config"):
  1299. return []
  1300. else:
  1301. handle = os.popen(LocateBinary(tool) + " --ldflags")
  1302. result = handle.read().strip()
  1303. handle.close()
  1304. if len(result) == 0: return []
  1305. libs = []
  1306. for l in result.split(" "):
  1307. if (l.startswith("-L")):
  1308. libs.append(l.replace("-L", "").replace("\"", "").strip())
  1309. return libs
  1310. def PkgConfigGetDefSymbols(pkgname, tool = "pkg-config"):
  1311. """Returns a dictionary of preprocessor definitions."""
  1312. if (sys.platform == "win32" or CrossCompiling() or not LocateBinary(tool)):
  1313. return []
  1314. if (tool == "pkg-config"):
  1315. handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --cflags " + pkgname)
  1316. else:
  1317. handle = os.popen(LocateBinary(tool) + " --cflags")
  1318. result = handle.read().strip()
  1319. handle.close()
  1320. if len(result) == 0: return {}
  1321. defs = {}
  1322. for l in result.split(" "):
  1323. if (l.startswith("-D")):
  1324. d = l.replace("-D", "").replace("\"", "").strip().split("=")
  1325. if d[0] in ('NDEBUG', '_DEBUG'):
  1326. # Setting one of these flags by accident could cause serious harm.
  1327. if GetVerbose():
  1328. print("Ignoring %s flag provided by %s" % (l, tool))
  1329. elif len(d) == 1:
  1330. defs[d[0]] = ""
  1331. else:
  1332. defs[d[0]] = d[1]
  1333. return defs
  1334. def PkgConfigEnable(opt, pkgname, tool = "pkg-config"):
  1335. """Adds the libraries and includes to IncDirectory, LibName and LibDirectory."""
  1336. for i in PkgConfigGetIncDirs(pkgname, tool):
  1337. IncDirectory(opt, i)
  1338. for i in PkgConfigGetLibDirs(pkgname, tool):
  1339. LibDirectory(opt, i)
  1340. for i in PkgConfigGetLibs(pkgname, tool):
  1341. LibName(opt, i)
  1342. for i, j in PkgConfigGetDefSymbols(pkgname, tool).items():
  1343. DefSymbol(opt, i, j)
  1344. def LocateLibrary(lib, lpath=[], prefer_static=False):
  1345. """Searches for the library in the search path, returning its path if found,
  1346. or None if it was not found."""
  1347. target = GetTarget()
  1348. if prefer_static and target != 'windows':
  1349. for dir in lpath:
  1350. if os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1351. return os.path.join(dir, 'lib%s.a' % lib)
  1352. for dir in lpath:
  1353. if target == 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.dylib' % lib)):
  1354. return os.path.join(dir, 'lib%s.dylib' % lib)
  1355. elif target != 'darwin' and os.path.isfile(os.path.join(dir, 'lib%s.so' % lib)):
  1356. return os.path.join(dir, 'lib%s.so' % lib)
  1357. elif os.path.isfile(os.path.join(dir, 'lib%s.a' % lib)):
  1358. return os.path.join(dir, 'lib%s.a' % lib)
  1359. return None
  1360. def SystemLibraryExists(lib):
  1361. result = LocateLibrary(lib, SYS_LIB_DIRS)
  1362. if result is not None:
  1363. return True
  1364. if GetHost() == "android" and GetTarget() == "android":
  1365. return ('lib%s.so' % lib) in ANDROID_SYS_LIBS
  1366. return False
  1367. def ChooseLib(libs, thirdparty=None):
  1368. """ Chooses a library from the parameters, in order of preference. Returns the first if none of them were found. """
  1369. lpath = []
  1370. if thirdparty is not None:
  1371. lpath.append(os.path.join(GetThirdpartyDir(), thirdparty.lower(), "lib"))
  1372. lpath += SYS_LIB_DIRS
  1373. for l in libs:
  1374. libname = l
  1375. if l.startswith("lib"):
  1376. libname = l[3:]
  1377. if LocateLibrary(libname, lpath):
  1378. return libname
  1379. if len(libs) > 0:
  1380. if VERBOSE:
  1381. print(ColorText("cyan", "Couldn't find any of the libraries " + ", ".join(libs)))
  1382. return libs[0]
  1383. def SmartPkgEnable(pkg, pkgconfig = None, libs = None, incs = None, defs = None, framework = None, target_pkg = None, tool = "pkg-config", thirdparty_dir = None):
  1384. global PKG_LIST_ALL
  1385. if (pkg in PkgListGet() and PkgSkip(pkg)):
  1386. return
  1387. if (target_pkg == "" or target_pkg == None):
  1388. target_pkg = pkg
  1389. if (pkgconfig == ""):
  1390. pkgconfig = None
  1391. if (framework == ""):
  1392. framework = None
  1393. if (libs == None or libs == ""):
  1394. libs = ()
  1395. elif (isinstance(libs, str)):
  1396. libs = (libs, )
  1397. if (incs == None or incs == ""):
  1398. incs = ()
  1399. elif (isinstance(incs, str)):
  1400. incs = (incs, )
  1401. if (defs == None or defs == "" or len(defs) == 0):
  1402. defs = {}
  1403. elif (isinstance(incs, str)):
  1404. defs = {defs : ""}
  1405. elif (isinstance(incs, list) or isinstance(incs, tuple) or isinstance(incs, set)):
  1406. olddefs = defs
  1407. defs = {}
  1408. for d in olddefs:
  1409. defs[d] = ""
  1410. custom_loc = PkgHasCustomLocation(pkg)
  1411. # Determine the location of the thirdparty directory.
  1412. if not thirdparty_dir:
  1413. thirdparty_dir = pkg.lower()
  1414. pkg_dir = os.path.join(GetThirdpartyDir(), thirdparty_dir)
  1415. # First check if the library can be found in the thirdparty directory.
  1416. if not custom_loc and os.path.isdir(pkg_dir):
  1417. if framework and os.path.isdir(os.path.join(pkg_dir, framework + ".framework")):
  1418. FrameworkDirectory(target_pkg, pkg_dir)
  1419. LibName(target_pkg, "-framework " + framework)
  1420. return
  1421. if os.path.isdir(os.path.join(pkg_dir, "include")):
  1422. IncDirectory(target_pkg, os.path.join(pkg_dir, "include"))
  1423. # Handle cases like freetype2 where the include dir is a subdir under "include"
  1424. for i in incs:
  1425. if os.path.isdir(os.path.join(pkg_dir, "include", i)):
  1426. IncDirectory(target_pkg, os.path.join(pkg_dir, "include", i))
  1427. lpath = [os.path.join(pkg_dir, "lib")]
  1428. if not PkgSkip("PYTHON"):
  1429. py_lib_dir = os.path.join(pkg_dir, "lib", SDK["PYTHONVERSION"])
  1430. if os.path.isdir(py_lib_dir):
  1431. lpath.append(py_lib_dir)
  1432. # TODO: check for a .pc file in the lib/pkgconfig/ dir
  1433. if (tool != None and os.path.isfile(os.path.join(pkg_dir, "bin", tool))):
  1434. tool = os.path.join(pkg_dir, "bin", tool)
  1435. for i in PkgConfigGetLibs(None, tool):
  1436. if i.startswith('-l'):
  1437. # To make sure we don't pick up the system copy, write out
  1438. # the full path instead.
  1439. libname = i[2:]
  1440. location = LocateLibrary(libname, lpath, prefer_static=True)
  1441. if location is not None:
  1442. LibName(target_pkg, location)
  1443. else:
  1444. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + pkg.lower() + GetColor())
  1445. LibName(target_pkg, i)
  1446. else:
  1447. LibName(target_pkg, i)
  1448. for i, j in PkgConfigGetDefSymbols(None, tool).items():
  1449. DefSymbol(target_pkg, i, j)
  1450. return
  1451. # Now search for the libraries in the package's lib directories.
  1452. for l in libs:
  1453. libname = l
  1454. if l.startswith("lib"):
  1455. libname = l[3:]
  1456. location = LocateLibrary(libname, lpath, prefer_static=True)
  1457. if location is not None:
  1458. # If it's a .so or .dylib we may have changed it and copied it to the built/lib dir.
  1459. if location.endswith('.so') or location.endswith('.dylib'):
  1460. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1461. LibName(target_pkg, location)
  1462. else:
  1463. # This is for backward compatibility - in the thirdparty dir,
  1464. # we kept some libs with "panda" prefix, like libpandatiff.
  1465. location = LocateLibrary("panda" + libname, lpath, prefer_static=True)
  1466. if location is not None:
  1467. if location.endswith('.so') or location.endswith('.dylib'):
  1468. location = os.path.join(GetOutputDir(), "lib", os.path.basename(location))
  1469. LibName(target_pkg, location)
  1470. else:
  1471. print(GetColor("cyan") + "Couldn't find library lib" + libname + " in thirdparty directory " + thirdparty_dir + GetColor())
  1472. for d, v in defs.values():
  1473. DefSymbol(target_pkg, d, v)
  1474. return
  1475. elif not custom_loc and GetHost() == "darwin" and framework != None:
  1476. prefix = SDK["MACOSX"]
  1477. if (os.path.isdir(prefix + "/Library/Frameworks/%s.framework" % framework) or
  1478. os.path.isdir(prefix + "/System/Library/Frameworks/%s.framework" % framework) or
  1479. os.path.isdir(prefix + "/Developer/Library/Frameworks/%s.framework" % framework) or
  1480. os.path.isdir(prefix + "/Users/%s/System/Library/Frameworks/%s.framework" % (getpass.getuser(), framework))):
  1481. LibName(target_pkg, "-framework " + framework)
  1482. for d, v in defs.values():
  1483. DefSymbol(target_pkg, d, v)
  1484. return
  1485. elif VERBOSE:
  1486. print(ColorText("cyan", "Couldn't find the framework %s" % (framework)))
  1487. elif not custom_loc and LocateBinary(tool) != None and (tool != "pkg-config" or pkgconfig != None):
  1488. if (isinstance(pkgconfig, str) or tool != "pkg-config"):
  1489. if (PkgConfigHavePkg(pkgconfig, tool)):
  1490. return PkgConfigEnable(target_pkg, pkgconfig, tool)
  1491. else:
  1492. have_all_pkgs = True
  1493. for pc in pkgconfig:
  1494. if (PkgConfigHavePkg(pc, tool)):
  1495. PkgConfigEnable(target_pkg, pc, tool)
  1496. else:
  1497. have_all_pkgs = False
  1498. if (have_all_pkgs):
  1499. return
  1500. if not custom_loc and pkgconfig is not None and not libs:
  1501. # pkg-config is all we can do, abort if it wasn't found.
  1502. if pkg in PkgListGet():
  1503. print("%sWARNING:%s Could not locate pkg-config package %s, excluding from build" % (GetColor("red"), GetColor(), pkgconfig))
  1504. PkgDisable(pkg)
  1505. else:
  1506. print("%sERROR:%s Could not locate pkg-config package %s, aborting build" % (GetColor("red"), GetColor(), pkgconfig))
  1507. exit()
  1508. else:
  1509. # Okay, our pkg-config attempts failed. Let's try locating the libs by ourselves.
  1510. have_pkg = True
  1511. for l in libs:
  1512. libname = l
  1513. if l.startswith("lib"):
  1514. libname = l[3:]
  1515. if custom_loc:
  1516. # Try searching in the package's LibDirectories.
  1517. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg]
  1518. location = LocateLibrary(libname, lpath)
  1519. if location is not None:
  1520. LibName(target_pkg, location)
  1521. else:
  1522. have_pkg = False
  1523. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1524. elif SystemLibraryExists(libname):
  1525. # It exists in a system library directory.
  1526. LibName(target_pkg, "-l" + libname)
  1527. else:
  1528. # Try searching in the package's LibDirectories.
  1529. lpath = [dir for ppkg, dir in LIBDIRECTORIES if pkg == ppkg or ppkg == "ALWAYS"]
  1530. location = LocateLibrary(libname, lpath)
  1531. if location is not None:
  1532. LibName(target_pkg, "-l" + libname)
  1533. else:
  1534. have_pkg = False
  1535. if VERBOSE or custom_loc:
  1536. print(GetColor("cyan") + "Couldn't find library lib" + libname + GetColor())
  1537. # Determine which include directories to look in.
  1538. incdirs = []
  1539. if not custom_loc:
  1540. incdirs += list(SYS_INC_DIRS)
  1541. for ppkg, pdir in INCDIRECTORIES[:]:
  1542. if pkg == ppkg or (ppkg == "ALWAYS" and not custom_loc):
  1543. incdirs.append(pdir)
  1544. if custom_loc and pkg != target_pkg:
  1545. IncDirectory(target_pkg, pdir)
  1546. # The incs list contains both subdirectories to explicitly add to
  1547. # the include path and header files to check the existence of.
  1548. for i in incs:
  1549. incdir = None
  1550. for dir in incdirs:
  1551. if len(glob.glob(os.path.join(dir, i))) > 0:
  1552. incdir = sorted(glob.glob(os.path.join(dir, i)))[-1]
  1553. # Note: It's possible to specify a file instead of a dir, for the sake of checking if it exists.
  1554. if incdir is None and (i.endswith('/Dense') or i.endswith(".h")):
  1555. have_pkg = False
  1556. if VERBOSE or custom_loc:
  1557. print(GetColor("cyan") + "Couldn't find header file " + i + GetColor())
  1558. if incdir is not None and os.path.isdir(incdir):
  1559. IncDirectory(target_pkg, incdir)
  1560. if not have_pkg:
  1561. if custom_loc:
  1562. print("%sERROR:%s Could not locate thirdparty package %s in specified directory, aborting build" % (GetColor("red"), GetColor(), pkg.lower()))
  1563. exit()
  1564. elif pkg in PkgListGet():
  1565. print("%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), pkg.lower()))
  1566. PkgDisable(pkg)
  1567. else:
  1568. print("%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), pkg.lower()))
  1569. exit()
  1570. ########################################################################
  1571. ##
  1572. ## SDK Location
  1573. ##
  1574. ## This section is concerned with locating the install directories
  1575. ## for various third-party packages. The results are stored in the
  1576. ## SDK table.
  1577. ##
  1578. ## Microsoft keeps changing the &*#$*& registry key for the DirectX SDK.
  1579. ## The only way to reliably find it is to search through the installer's
  1580. ## uninstall-directories, look in each one, and see if it contains the
  1581. ## relevant files.
  1582. ##
  1583. ########################################################################
  1584. SDK = {}
  1585. def GetSdkDir(sdkname, sdkkey = None):
  1586. # Returns the default SDK directory. If it exists,
  1587. # and sdkkey is not None, it is put in SDK[sdkkey].
  1588. # Note: return value may not be an existing path.
  1589. sdkbase = "sdks"
  1590. if "MAKEPANDA_SDKS" in os.environ:
  1591. sdkbase = os.environ["MAKEPANDA_SDKS"]
  1592. sdir = sdkbase[:]
  1593. target = GetTarget()
  1594. target_arch = GetTargetArch()
  1595. if target == 'windows':
  1596. if target_arch == 'x64':
  1597. sdir += "/win64"
  1598. else:
  1599. sdir += "/win32"
  1600. elif target == 'linux':
  1601. sdir += "/linux"
  1602. sdir += platform.architecture()[0][:2]
  1603. elif target == 'darwin':
  1604. sdir += "/macosx"
  1605. sdir += "/" + sdkname
  1606. # If it does not exist, try the old location.
  1607. if (not os.path.isdir(sdir)):
  1608. sdir = sdkbase + "/" + sdir
  1609. if (target == 'linux'):
  1610. sdir += "-linux"
  1611. sdir += platform.architecture()[0][:2]
  1612. elif (target == "darwin"):
  1613. sdir += "-osx"
  1614. if (sdkkey and os.path.isdir(sdir)):
  1615. SDK[sdkkey] = sdir
  1616. return sdir
  1617. def SdkLocateDirectX( strMode = 'default' ):
  1618. if (GetHost() != "windows"): return
  1619. if strMode == 'default':
  1620. GetSdkDir("directx9", "DX9")
  1621. if ("DX9" not in SDK):
  1622. strMode = 'latest'
  1623. if strMode == 'latest':
  1624. ## We first try to locate the August SDK in 64 bits, then 32.
  1625. if ("DX9" not in SDK):
  1626. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1627. if (dir != 0):
  1628. print("Using DirectX SDK June 2010")
  1629. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1630. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1631. if ("DX9" not in SDK):
  1632. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1633. if (dir != 0):
  1634. print("Using DirectX SDK June 2010")
  1635. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1636. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1637. if ("DX9" not in SDK):
  1638. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1639. if os.path.isdir(dir):
  1640. print("Using DirectX SDK June 2010")
  1641. SDK["DX9"] = dir
  1642. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1643. if ("DX9" not in SDK):
  1644. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1645. if os.path.isdir(dir):
  1646. print("Using DirectX SDK June 2010")
  1647. SDK["DX9"] = dir
  1648. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1649. if ("DX9" not in SDK):
  1650. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1651. if (dir != 0):
  1652. print("Using DirectX SDK Aug 2009")
  1653. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1654. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1655. if ("DX9" not in SDK):
  1656. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1657. if (dir != 0):
  1658. print("Using DirectX SDK Aug 2009")
  1659. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1660. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1661. if ("DX9" not in SDK):
  1662. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1663. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1664. if (dir != 0):
  1665. print("Using DirectX SDK March 2009")
  1666. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1667. archStr = GetTargetArch()
  1668. if ("DX9" not in SDK):
  1669. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1670. for subdir in ListRegistryKeys(uninstaller):
  1671. if (subdir[0]=="{"):
  1672. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1673. if (dir != 0):
  1674. if (("DX9" not in SDK) and
  1675. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1676. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1677. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1678. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1679. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1680. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1681. if ("DX9" not in SDK):
  1682. return
  1683. elif strMode == 'jun2010':
  1684. if ("DX9" not in SDK):
  1685. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1686. if (dir != 0):
  1687. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1688. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1689. if ("DX9" not in SDK):
  1690. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (June 2010)", "InstallPath")
  1691. if (dir != 0):
  1692. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1693. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1694. if ("DX9" not in SDK):
  1695. dir = "C:/Program Files (x86)/Microsoft DirectX SDK (June 2010)"
  1696. if os.path.isdir(dir):
  1697. SDK["DX9"] = dir
  1698. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1699. if ("DX9" not in SDK):
  1700. dir = "C:/Program Files/Microsoft DirectX SDK (June 2010)"
  1701. if os.path.isdir(dir):
  1702. SDK["DX9"] = dir
  1703. SDK["GENERIC_DXERR_LIBRARY"] = 1
  1704. if ("DX9" not in SDK):
  1705. exit("Couldn't find DirectX June2010 SDK")
  1706. else:
  1707. print("Found DirectX SDK June 2010")
  1708. elif strMode == 'aug2009':
  1709. if ("DX9" not in SDK):
  1710. dir = GetRegistryKey("SOFTWARE\\Wow6432Node\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1711. if (dir != 0):
  1712. print("Found DirectX SDK Aug 2009")
  1713. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1714. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1715. if ("DX9" not in SDK):
  1716. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (August 2009)", "InstallPath")
  1717. if (dir != 0):
  1718. print("Found DirectX SDK Aug 2009")
  1719. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1720. SDK["GENERIC_DXERR_LIBRARY"] = 1;
  1721. if ("DX9" not in SDK):
  1722. exit("Couldn't find DirectX Aug 2009 SDK")
  1723. elif strMode == 'mar2009':
  1724. if ("DX9" not in SDK):
  1725. ## Try to locate the key within the "new" March 2009 location in the registry (yecch):
  1726. dir = GetRegistryKey("SOFTWARE\\Microsoft\\DirectX\\Microsoft DirectX SDK (March 2009)", "InstallPath")
  1727. if (dir != 0):
  1728. print("Found DirectX SDK March 2009")
  1729. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1730. if ("DX9" not in SDK):
  1731. exit("Couldn't find DirectX March 2009 SDK")
  1732. elif strMode == 'aug2006':
  1733. archStr = GetTargetArch()
  1734. if ("DX9" not in SDK):
  1735. uninstaller = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  1736. for subdir in ListRegistryKeys(uninstaller):
  1737. if (subdir[0]=="{"):
  1738. dir = GetRegistryKey(uninstaller+"\\"+subdir, "InstallLocation")
  1739. if (dir != 0):
  1740. if (("DX9" not in SDK) and
  1741. (os.path.isfile(dir+"\\Include\\d3d9.h")) and
  1742. (os.path.isfile(dir+"\\Include\\d3dx9.h")) and
  1743. (os.path.isfile(dir+"\\Include\\dxsdkver.h")) and
  1744. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3d9.lib")) and
  1745. (os.path.isfile(dir+"\\Lib\\" + archStr + "\\d3dx9.lib"))):
  1746. SDK["DX9"] = dir.replace("\\", "/").rstrip("/")
  1747. if ("DX9" not in SDK):
  1748. exit("Couldn't find a DirectX Aug 2006 SDK")
  1749. if ("DX9" in SDK):
  1750. SDK["DIRECTCAM"] = SDK["DX9"]
  1751. def SdkLocateMaya():
  1752. for (ver, key) in MAYAVERSIONINFO:
  1753. if (PkgSkip(ver)==0 and ver not in SDK):
  1754. GetSdkDir(ver.lower().replace("x",""), ver)
  1755. if (not ver in SDK):
  1756. if (GetHost() == "windows"):
  1757. for dev in ["Alias|Wavefront","Alias","Autodesk"]:
  1758. fullkey="SOFTWARE\\"+dev+"\\Maya\\"+key+"\\Setup\\InstallPath"
  1759. res = GetRegistryKey(fullkey, "MAYA_INSTALL_LOCATION", override64=False)
  1760. if (res != 0):
  1761. res = res.replace("\\", "/").rstrip("/")
  1762. SDK[ver] = res
  1763. elif (GetHost() == "darwin"):
  1764. ddir = "/Applications/Autodesk/maya"+key
  1765. if (os.path.isdir(ddir)): SDK[ver] = ddir
  1766. else:
  1767. if (GetTargetArch() in ("x86_64", "amd64")):
  1768. ddir1 = "/usr/autodesk/maya"+key+"-x64"
  1769. ddir2 = "/usr/aw/maya"+key+"-x64"
  1770. else:
  1771. ddir1 = "/usr/autodesk/maya"+key
  1772. ddir2 = "/usr/aw/maya"+key
  1773. if (os.path.isdir(ddir1)): SDK[ver] = ddir1
  1774. elif (os.path.isdir(ddir2)): SDK[ver] = ddir2
  1775. def SdkLocateMax():
  1776. if (GetHost() != "windows"): return
  1777. for version,key1,key2,subdir in MAXVERSIONINFO:
  1778. if (PkgSkip(version)==0):
  1779. if (version not in SDK):
  1780. GetSdkDir("maxsdk"+version.lower()[3:], version)
  1781. GetSdkDir("maxsdk"+version.lower()[3:], version+"CS")
  1782. if (not version in SDK):
  1783. top = GetRegistryKey(key1,key2)
  1784. if (top != 0):
  1785. SDK[version] = top + "maxsdk"
  1786. if (os.path.isdir(top + "\\" + subdir)!=0):
  1787. SDK[version+"CS"] = top + subdir
  1788. def SdkLocatePython(prefer_thirdparty_python=False):
  1789. if PkgSkip("PYTHON"):
  1790. # We're not compiling with Python support. We still need to set this
  1791. # in case we want to run any scripts that use Python, though.
  1792. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1793. return
  1794. abiflags = getattr(sys, 'abiflags', '')
  1795. if GetTarget() == 'windows':
  1796. sdkdir = GetThirdpartyBase() + "/win-python"
  1797. if sys.version_info >= (3, 0):
  1798. # Python 3 build...
  1799. sdkdir += "%d.%d" % sys.version_info[:2]
  1800. if GetOptimize() <= 2:
  1801. sdkdir += "-dbg"
  1802. if GetTargetArch() == 'x64':
  1803. sdkdir += "-x64"
  1804. SDK["PYTHON"] = sdkdir
  1805. SDK["PYTHONEXEC"] = SDK["PYTHON"].replace('\\', '/') + "/python"
  1806. if (GetOptimize() <= 2):
  1807. SDK["PYTHONEXEC"] += "_d.exe"
  1808. else:
  1809. SDK["PYTHONEXEC"] += ".exe"
  1810. if (not os.path.isfile(SDK["PYTHONEXEC"])):
  1811. exit("Could not find %s!" % SDK["PYTHONEXEC"])
  1812. # Determine which version it is by checking which dll is in the directory.
  1813. if (GetOptimize() <= 2):
  1814. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9]_d.dll")
  1815. else:
  1816. py_dlls = glob.glob(SDK["PYTHON"] + "/python[0-9][0-9].dll")
  1817. if len(py_dlls) == 0:
  1818. exit("Could not find the Python dll in %s." % (SDK["PYTHON"]))
  1819. elif len(py_dlls) > 1:
  1820. exit("Found multiple Python dlls in %s." % (SDK["PYTHON"]))
  1821. py_dll = os.path.basename(py_dlls[0])
  1822. ver = py_dll[6] + "." + py_dll[7]
  1823. SDK["PYTHONVERSION"] = "python" + ver
  1824. os.environ["PYTHONHOME"] = SDK["PYTHON"]
  1825. if sys.version[:3] != ver:
  1826. print("Warning: running makepanda with Python %s, but building Panda3D with Python %s." % (sys.version[:3], ver))
  1827. elif CrossCompiling() or (prefer_thirdparty_python and os.path.isdir(os.path.join(GetThirdpartyDir(), "python"))):
  1828. tp_python = os.path.join(GetThirdpartyDir(), "python")
  1829. if GetTarget() == 'darwin':
  1830. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].dylib")
  1831. else:
  1832. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].so")
  1833. if len(py_libs) == 0:
  1834. py_libs = glob.glob(tp_python + "/lib/libpython[0-9].[0-9].a")
  1835. if len(py_libs) == 0:
  1836. exit("Could not find the Python library in %s." % (tp_python))
  1837. elif len(py_libs) > 1:
  1838. exit("Found multiple Python libraries in %s." % (tp_python))
  1839. py_lib = os.path.basename(py_libs[0])
  1840. SDK["PYTHONVERSION"] = "python" + py_lib[9] + "." + py_lib[11]
  1841. SDK["PYTHONEXEC"] = tp_python + "/bin/" + SDK["PYTHONVERSION"]
  1842. SDK["PYTHON"] = tp_python + "/include/" + SDK["PYTHONVERSION"]
  1843. elif GetTarget() == 'darwin':
  1844. # On macOS, search for the Python framework directory matching the
  1845. # version number of our current Python version.
  1846. sysroot = SDK.get("MACOSX", "")
  1847. version = sysconfig.get_python_version()
  1848. py_fwx = "{0}/System/Library/Frameworks/Python.framework/Versions/{1}".format(sysroot, version)
  1849. if not os.path.exists(py_fwx):
  1850. # Fall back to looking on the system.
  1851. py_fwx = "/Library/Frameworks/Python.framework/Versions/" + version
  1852. if not os.path.exists(py_fwx):
  1853. exit("Could not locate Python installation at %s" % (py_fwx))
  1854. SDK["PYTHON"] = py_fwx + "/Headers"
  1855. SDK["PYTHONVERSION"] = "python" + version + abiflags
  1856. SDK["PYTHONEXEC"] = py_fwx + "/bin/python" + version
  1857. # Avoid choosing the one in the thirdparty package dir.
  1858. PkgSetCustomLocation("PYTHON")
  1859. IncDirectory("PYTHON", py_fwx + "/include")
  1860. LibDirectory("PYTHON", py_fwx + "/lib")
  1861. #elif GetTarget() == 'windows':
  1862. # SDK["PYTHON"] = os.path.dirname(sysconfig.get_python_inc())
  1863. # SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version()
  1864. # SDK["PYTHONEXEC"] = sys.executable
  1865. else:
  1866. SDK["PYTHON"] = sysconfig.get_python_inc()
  1867. SDK["PYTHONVERSION"] = "python" + sysconfig.get_python_version() + abiflags
  1868. SDK["PYTHONEXEC"] = os.path.realpath(sys.executable)
  1869. if CrossCompiling():
  1870. # We need a version of Python we can run.
  1871. SDK["PYTHONEXEC"] = sys.executable
  1872. host_version = "python" + sysconfig.get_python_version() + abiflags
  1873. if SDK["PYTHONVERSION"] != host_version:
  1874. exit("Host Python version (%s) must be the same as target Python version (%s)!" % (host_version, SDK["PYTHONVERSION"]))
  1875. if GetVerbose():
  1876. print("Using Python %s build located at %s" % (SDK["PYTHONVERSION"][6:9], SDK["PYTHON"]))
  1877. else:
  1878. print("Using Python %s" % (SDK["PYTHONVERSION"][6:9]))
  1879. def SdkLocateVisualStudio(version=(10,0)):
  1880. if (GetHost() != "windows"): return
  1881. try:
  1882. msvcinfo = MSVCVERSIONINFO[version]
  1883. except:
  1884. exit("Couldn't get Visual Studio infomation with MSVC %s.%s version." % version)
  1885. vsversion = msvcinfo["vsversion"]
  1886. vsversion_str = "%s.%s" % vsversion
  1887. version_str = "%s.%s" % version
  1888. # try to use vswhere.exe
  1889. vswhere_path = LocateBinary("vswhere.exe")
  1890. if not vswhere_path:
  1891. if sys.platform == 'cygwin':
  1892. vswhere_path = "/cygdrive/c/Program Files/Microsoft Visual Studio/Installer/vswhere.exe"
  1893. else:
  1894. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles()
  1895. if not os.path.isfile(vswhere_path):
  1896. vswhere_path = None
  1897. if not vswhere_path:
  1898. if sys.platform == 'cygwin':
  1899. vswhere_path = "/cygdrive/c/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe"
  1900. else:
  1901. vswhere_path = "%s\\Microsoft Visual Studio\\Installer\\vswhere.exe" % GetProgramFiles_x86()
  1902. if not os.path.isfile(vswhere_path):
  1903. vswhere_path = None
  1904. vsdir = 0
  1905. if vswhere_path:
  1906. min_vsversion = vsversion_str
  1907. max_vsversion = "%s.%s" % (vsversion[0]+1, 0)
  1908. vswhere_cmd = ["vswhere.exe", "-legacy", "-property", "installationPath",
  1909. "-version", "[{},{})".format(min_vsversion, max_vsversion)]
  1910. handle = subprocess.Popen(vswhere_cmd, executable=vswhere_path, stdout=subprocess.PIPE)
  1911. found_paths = handle.communicate()[0].splitlines()
  1912. if found_paths:
  1913. vsdir = found_paths[0].decode("utf-8") + "\\"
  1914. # try to use registry
  1915. if (vsdir == 0):
  1916. vsdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7", vsversion_str)
  1917. vcdir = GetRegistryKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", version_str)
  1918. if (vsdir != 0):
  1919. SDK["VISUALSTUDIO"] = vsdir
  1920. elif (vcdir != 0) and (vcdir[-4:] == "\\VC\\"):
  1921. vcdir = vcdir[:-3]
  1922. SDK["VISUALSTUDIO"] = vcdir
  1923. elif (os.path.isfile("C:\\Program Files\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1924. SDK["VISUALSTUDIO"] = "C:\\Program Files\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1925. elif (os.path.isfile("C:\\Program Files (x86)\\Microsoft Visual Studio %s\\VC\\bin\\cl.exe" % (vsversion_str))):
  1926. SDK["VISUALSTUDIO"] = "C:\\Program Files (x86)\\Microsoft Visual Studio %s\\" % (vsversion_str)
  1927. elif "VCINSTALLDIR" in os.environ:
  1928. vcdir = os.environ["VCINSTALLDIR"]
  1929. if (vcdir[-3:] == "\\VC"):
  1930. vcdir = vcdir[:-2]
  1931. elif (vcdir[-4:] == "\\VC\\"):
  1932. vcdir = vcdir[:-3]
  1933. SDK["VISUALSTUDIO"] = vcdir
  1934. else:
  1935. exit("Couldn't find %s. To use a different version, use the --msvc-version option." % msvcinfo["vsname"])
  1936. SDK["MSVC_VERSION"] = version
  1937. SDK["VISUALSTUDIO_VERSION"] = vsversion
  1938. if GetVerbose():
  1939. print("Using %s located at %s" % (msvcinfo["vsname"], SDK["VISUALSTUDIO"]))
  1940. else:
  1941. print("Using %s" % (msvcinfo["vsname"]))
  1942. print("Using MSVC %s" % version_str)
  1943. def SdkLocateWindows(version = '7.1'):
  1944. if GetTarget() != "windows" or GetHost() != "windows":
  1945. return
  1946. version = version.upper()
  1947. if version == '10':
  1948. version = '10.0'
  1949. if version.startswith('10.') and version.count('.') == 1:
  1950. # Choose the latest version of the Windows 10 SDK.
  1951. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  1952. # Fallback in case we can't read the registry.
  1953. if not platsdk or not os.path.isdir(platsdk):
  1954. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  1955. if platsdk and os.path.isdir(platsdk):
  1956. incdirs = glob.glob(os.path.join(platsdk, 'Include', version + '.*.*'))
  1957. max_version = ()
  1958. for dir in incdirs:
  1959. verstring = os.path.basename(dir)
  1960. # Check that the important include directories exist.
  1961. if not os.path.isdir(os.path.join(dir, 'ucrt')):
  1962. continue
  1963. if not os.path.isdir(os.path.join(dir, 'shared')):
  1964. continue
  1965. if not os.path.isdir(os.path.join(dir, 'um')):
  1966. continue
  1967. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'ucrt')):
  1968. continue
  1969. if not os.path.isdir(os.path.join(platsdk, 'Lib', verstring, 'um')):
  1970. continue
  1971. print(verstring)
  1972. vertuple = tuple(map(int, verstring.split('.')))
  1973. if vertuple > max_version:
  1974. version = verstring
  1975. max_version = vertuple
  1976. if not max_version:
  1977. # No suitable version found.
  1978. platsdk = None
  1979. elif version.startswith('10.'):
  1980. # We chose a specific version of the Windows 10 SDK. Verify it exists.
  1981. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  1982. # Fallback in case we can't read the registry.
  1983. if not platsdk or not os.path.isdir(platsdk):
  1984. platsdk = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  1985. if version.count('.') == 2:
  1986. version += '.0'
  1987. if platsdk and not os.path.isdir(os.path.join(platsdk, 'Include', version)):
  1988. platsdk = None
  1989. elif version == '8.1':
  1990. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot81")
  1991. # Fallback in case we can't read the registry.
  1992. if not platsdk or not os.path.isdir(platsdk):
  1993. platsdk = "C:\\Program Files (x86)\\Windows Kits\\8.1\\"
  1994. elif version == '8.0':
  1995. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot")
  1996. else:
  1997. platsdk = GetRegistryKey("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v" + version, "InstallationFolder")
  1998. if not platsdk or not os.path.isdir(platsdk):
  1999. # Most common location. Worth a try.
  2000. platsdk = GetProgramFiles() + "\\Microsoft SDKs\\Windows\\v" + version
  2001. if not os.path.isdir(platsdk):
  2002. if not version.endswith('A'):
  2003. # Try the stripped-down version that is bundled with Visual Studio.
  2004. return SdkLocateWindows(version + 'A')
  2005. platsdk = None
  2006. if not platsdk or not os.path.isdir(platsdk):
  2007. exit("Couldn't find Windows SDK version %s. To use a different version, use the --windows-sdk option." % (version))
  2008. if not platsdk.endswith("\\"):
  2009. platsdk += "\\"
  2010. SDK["MSPLATFORM"] = platsdk
  2011. SDK["MSPLATFORM_VERSION"] = version
  2012. if GetVerbose():
  2013. print("Using Windows SDK %s located at %s" % (version, platsdk))
  2014. else:
  2015. print("Using Windows SDK %s" % (version))
  2016. def SdkLocateMacOSX(osxtarget = None):
  2017. if (GetHost() != "darwin"): return
  2018. if (osxtarget != None):
  2019. sdkname = "MacOSX%d.%d" % osxtarget
  2020. if (os.path.exists("/Developer/SDKs/%su.sdk" % sdkname)):
  2021. SDK["MACOSX"] = "/Developer/SDKs/%su.sdk" % sdkname
  2022. elif (os.path.exists("/Developer/SDKs/%s.sdk" % sdkname)):
  2023. SDK["MACOSX"] = "/Developer/SDKs/%s.sdk" % sdkname
  2024. elif (os.path.exists("/Developer/SDKs/%s.0.sdk" % sdkname)):
  2025. SDK["MACOSX"] = "/Developer/SDKs/%s.0.sdk" % sdkname
  2026. elif (os.path.exists("/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname)):
  2027. SDK["MACOSX"] = "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % sdkname
  2028. else:
  2029. handle = os.popen("xcode-select -print-path")
  2030. result = handle.read().strip().rstrip('/')
  2031. handle.close()
  2032. if (os.path.exists("%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (result, sdkname))):
  2033. SDK["MACOSX"] = "%s/Platforms/MacOSX.platform/Developer/SDKs/%s.sdk" % (result, sdkname)
  2034. else:
  2035. exit("Couldn't find any MacOSX SDK for OSX version %s!" % sdkname)
  2036. else:
  2037. SDK["MACOSX"] = ""
  2038. # Latest first
  2039. PHYSXVERSIONINFO = [
  2040. ("PHYSX284", "v2.8.4"),
  2041. ("PHYSX283", "v2.8.3"),
  2042. ("PHYSX281", "v2.8.1"),
  2043. ]
  2044. def SdkLocatePhysX():
  2045. # First check for a physx directory in sdks.
  2046. dir = GetSdkDir("physx")
  2047. if (dir and os.path.isdir(dir)):
  2048. SDK["PHYSX"] = dir
  2049. SDK["PHYSXLIBS"] = dir + "/lib"
  2050. return
  2051. if CrossCompiling():
  2052. return
  2053. # Try to find a PhysX installation on the system.
  2054. for (ver, key) in PHYSXVERSIONINFO:
  2055. if (GetHost() == "windows"):
  2056. folders = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\Folders"
  2057. for folder in ListRegistryValues(folders):
  2058. if folder.endswith("NVIDIA PhysX SDK\\%s\\SDKs\\" % key) or \
  2059. folder.endswith("NVIDIA PhysX SDK\\%s_win\\SDKs\\" % key):
  2060. SDK["PHYSX"] = folder
  2061. if GetTargetArch() == 'x64':
  2062. SDK["PHYSXLIBS"] = folder + "/lib/win64"
  2063. AddToPathEnv("PATH", folder + "/../Bin/win64/")
  2064. else:
  2065. SDK["PHYSXLIBS"] = folder + "/lib/win32"
  2066. AddToPathEnv("PATH", folder + "/../Bin/win32/")
  2067. return
  2068. elif (GetHost() == "linux"):
  2069. incpath = "/usr/include/PhysX/%s/SDKs" % key
  2070. libpath = "/usr/lib/PhysX/%s" % key
  2071. if (os.path.isdir(incpath) and os.path.isdir(libpath)):
  2072. SDK["PHYSX"] = incpath
  2073. SDK["PHYSXLIBS"] = libpath
  2074. return
  2075. def SdkLocateSpeedTree():
  2076. # Look for all of the SpeedTree SDK directories within the
  2077. # sdks/win32/speedtree dir, and pick the highest-numbered one.
  2078. dir = GetSdkDir("speedtree")
  2079. if not os.path.exists(dir):
  2080. return
  2081. speedtrees = []
  2082. for dirname in os.listdir(dir):
  2083. if dirname.startswith('SpeedTree SDK v'):
  2084. version = dirname[15:].split()[0]
  2085. version = tuple(map(int, version.split('.')))
  2086. speedtrees.append((version, dirname))
  2087. if not speedtrees:
  2088. # No installed SpeedTree SDK.
  2089. return
  2090. speedtrees.sort()
  2091. version, dirname = speedtrees[-1]
  2092. SDK["SPEEDTREE"] = os.path.join(dir, dirname)
  2093. SDK["SPEEDTREEAPI"] = "OpenGL"
  2094. SDK["SPEEDTREEVERSION"] = '%s.%s' % (version[0], version[1])
  2095. def SdkLocateAndroid():
  2096. """This actually locates the Android NDK, not the Android SDK.
  2097. NDK_ROOT must be set to its root directory."""
  2098. global TOOLCHAIN_PREFIX
  2099. if GetTarget() != 'android':
  2100. return
  2101. # Allow ANDROID_API/ANDROID_ABI to be used in makepanda.py.
  2102. api = ANDROID_API
  2103. SDK["ANDROID_API"] = api
  2104. abi = ANDROID_ABI
  2105. SDK["ANDROID_ABI"] = abi
  2106. SDK["ANDROID_TRIPLE"] = ANDROID_TRIPLE
  2107. if GetHost() == 'android':
  2108. return
  2109. # Determine the NDK installation directory.
  2110. if 'NDK_ROOT' not in os.environ:
  2111. exit('NDK_ROOT must be set when compiling for Android!')
  2112. ndk_root = os.environ["NDK_ROOT"]
  2113. if not os.path.isdir(ndk_root):
  2114. exit("Cannot find %s. Please install Android NDK and set NDK_ROOT." % (ndk_root))
  2115. SDK["ANDROID_NDK"] = ndk_root
  2116. # Determine the toolchain location.
  2117. prebuilt_dir = os.path.join(ndk_root, 'toolchains', 'llvm', 'prebuilt')
  2118. if not os.path.isdir(prebuilt_dir):
  2119. exit('Not found: %s' % (prebuilt_dir))
  2120. host_tag = GetHost() + '-x86'
  2121. if host_64:
  2122. host_tag += '_64'
  2123. elif host_tag == 'windows-x86':
  2124. host_tag = 'windows'
  2125. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2126. if host_tag == 'windows-x86_64' and not os.path.isdir(prebuilt_dir):
  2127. # Try the 32-bits toolchain instead.
  2128. host_tag = 'windows'
  2129. prebuilt_dir = os.path.join(prebuilt_dir, host_tag)
  2130. SDK["ANDROID_TOOLCHAIN"] = prebuilt_dir
  2131. # And locate the GCC toolchain, which is needed for some tools (eg. as/ld)
  2132. arch = GetTargetArch()
  2133. for opt in (TOOLCHAIN_PREFIX + '4.9', arch + '-4.9', TOOLCHAIN_PREFIX + '4.8', arch + '-4.8'):
  2134. if os.path.isdir(os.path.join(ndk_root, 'toolchains', opt)):
  2135. SDK["ANDROID_GCC_TOOLCHAIN"] = os.path.join(ndk_root, 'toolchains', opt, 'prebuilt', host_tag)
  2136. break
  2137. # The prebuilt binaries have no toolchain prefix.
  2138. TOOLCHAIN_PREFIX = ''
  2139. # Determine the sysroot directory.
  2140. if arch == 'armv7a':
  2141. arch_dir = 'arch-arm'
  2142. elif arch == 'aarch64':
  2143. arch_dir = 'arch-arm64'
  2144. else:
  2145. arch_dir = 'arch-' + arch
  2146. SDK["SYSROOT"] = os.path.join(ndk_root, 'platforms', 'android-%s' % (api), arch_dir).replace('\\', '/')
  2147. #IncDirectory("ALWAYS", os.path.join(SDK["SYSROOT"], 'usr', 'include'))
  2148. # Starting with NDK r16, libc++ is the recommended STL to use.
  2149. stdlibc = os.path.join(ndk_root, 'sources', 'cxx-stl', 'llvm-libc++')
  2150. IncDirectory("ALWAYS", os.path.join(stdlibc, 'include').replace('\\', '/'))
  2151. LibDirectory("ALWAYS", os.path.join(stdlibc, 'libs', abi).replace('\\', '/'))
  2152. stl_lib = os.path.join(stdlibc, 'libs', abi, 'libc++_shared.so')
  2153. LibName("ALWAYS", stl_lib.replace('\\', '/'))
  2154. CopyFile(os.path.join(GetOutputDir(), 'lib', 'libc++_shared.so'), stl_lib)
  2155. # The Android support library polyfills C++ features not available in the
  2156. # STL that ships with Android.
  2157. support = os.path.join(ndk_root, 'sources', 'android', 'support', 'include')
  2158. IncDirectory("ALWAYS", support.replace('\\', '/'))
  2159. LibName("ALWAYS", "-landroid_support")
  2160. def SdkLocateVulkan():
  2161. if GetHost() != 'windows' or GetTarget() != 'windows':
  2162. return
  2163. path = 'C:/VulkanSDK'
  2164. if os.path.isdir(path):
  2165. # Enumerate the available Vulkan SDK versions.
  2166. versions = []
  2167. for dir in os.listdir(path):
  2168. try:
  2169. versions.append(tuple([int(i) for i in dir.split('.')]))
  2170. except ValueError:
  2171. pass
  2172. # Use the latest version.
  2173. versions.sort()
  2174. version = '.'.join([str(i) for i in versions[-1]])
  2175. print("Using Vulkan SDK %s" % (version))
  2176. SDK["VULKAN"] = path + '/' + version
  2177. ########################################################################
  2178. ##
  2179. ## SDK Auto-Disables
  2180. ##
  2181. ## Disable packages whose SDKs could not be found.
  2182. ##
  2183. ########################################################################
  2184. def SdkAutoDisableDirectX():
  2185. for ver in DXVERSIONS + ["DIRECTCAM"]:
  2186. if (PkgSkip(ver)==0):
  2187. if (ver not in SDK):
  2188. if (GetHost() == "windows"):
  2189. WARNINGS.append("I cannot locate SDK for "+ver)
  2190. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2191. PkgDisable(ver)
  2192. else:
  2193. WARNINGS.append("Using "+ver+" sdk: "+SDK[ver])
  2194. def SdkAutoDisableMaya():
  2195. for (ver,key) in MAYAVERSIONINFO:
  2196. if (ver not in SDK) and (PkgSkip(ver)==0):
  2197. if (GetHost() == "windows"):
  2198. WARNINGS.append("The registry does not appear to contain a pointer to the "+ver+" SDK.")
  2199. else:
  2200. WARNINGS.append("I cannot locate SDK for "+ver)
  2201. WARNINGS.append("I have automatically added this command-line option: --no-"+ver.lower())
  2202. PkgDisable(ver)
  2203. def SdkAutoDisableMax():
  2204. for version,key1,key2,subdir in MAXVERSIONINFO:
  2205. if (PkgSkip(version)==0) and ((version not in SDK) or (version+"CS" not in SDK)):
  2206. if (GetHost() == "windows"):
  2207. if (version in SDK):
  2208. WARNINGS.append("Your copy of "+version+" does not include the character studio SDK")
  2209. else:
  2210. WARNINGS.append("The registry does not appear to contain a pointer to "+version)
  2211. WARNINGS.append("I have automatically added this command-line option: --no-"+version.lower())
  2212. PkgDisable(version)
  2213. def SdkAutoDisablePhysX():
  2214. if ("PHYSX" not in SDK) and (PkgSkip("PHYSX")==0):
  2215. PkgDisable("PHYSX")
  2216. WARNINGS.append("I cannot locate SDK for PhysX")
  2217. WARNINGS.append("I have automatically added this command-line option: --no-physx")
  2218. def SdkAutoDisableSpeedTree():
  2219. if ("SPEEDTREE" not in SDK) and (PkgSkip("SPEEDTREE")==0):
  2220. PkgDisable("SPEEDTREE")
  2221. WARNINGS.append("I cannot locate SDK for SpeedTree")
  2222. WARNINGS.append("I have automatically added this command-line option: --no-speedtree")
  2223. ########################################################################
  2224. ##
  2225. ## Visual Studio comes with a script called VSVARS32.BAT, which
  2226. ## you need to run before using visual studio command-line tools.
  2227. ## The following python subroutine serves the same purpose.
  2228. ##
  2229. ########################################################################
  2230. def AddToPathEnv(path,add):
  2231. if path in os.environ:
  2232. if sys.platform == 'cygwin' and path != "PATH":
  2233. # INCLUDE, LIB, etc. must remain in Windows-style in cygwin.
  2234. os.environ[path] = add + ';' + os.environ[path]
  2235. else:
  2236. os.environ[path] = add + os.pathsep + os.environ[path]
  2237. else:
  2238. os.environ[path] = add
  2239. def SetupVisualStudioEnviron():
  2240. if ("VISUALSTUDIO" not in SDK):
  2241. exit("Could not find Visual Studio install directory")
  2242. if ("MSPLATFORM" not in SDK):
  2243. exit("Could not find the Microsoft Platform SDK")
  2244. if (SDK["VISUALSTUDIO_VERSION"] >= (15,0)):
  2245. try:
  2246. vsver_file = open(os.path.join(SDK["VISUALSTUDIO"],
  2247. "VC\\Auxiliary\\Build\\Microsoft.VCToolsVersion.default.txt"), "r")
  2248. SDK["VCTOOLSVERSION"] = vsver_file.readline().strip()
  2249. vcdir_suffix = "VC\\Tools\\MSVC\\%s\\" % SDK["VCTOOLSVERSION"]
  2250. except:
  2251. exit("Couldn't find tool version of %s." % MSVCVERSIONINFO[SDK["MSVC_VERSION"]]["vsname"])
  2252. else:
  2253. vcdir_suffix = "VC\\"
  2254. os.environ["VCINSTALLDIR"] = SDK["VISUALSTUDIO"] + vcdir_suffix
  2255. os.environ["WindowsSdkDir"] = SDK["MSPLATFORM"]
  2256. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2257. # Determine the directories to look in based on the architecture.
  2258. arch = GetTargetArch()
  2259. bindir = ""
  2260. libdir = ""
  2261. if ("VCTOOLSVERSION" in SDK):
  2262. bindir = "Host" + GetHostArch().upper() + "\\" + arch
  2263. libdir = arch
  2264. else:
  2265. if (arch == 'x64'):
  2266. bindir = 'amd64'
  2267. libdir = 'amd64'
  2268. elif (arch != 'x86'):
  2269. bindir = arch
  2270. libdir = arch
  2271. if (arch != 'x86' and GetHostArch() == 'x86'):
  2272. # Special version of the tools that run on x86.
  2273. bindir = 'x86_' + bindir
  2274. vc_binpath = SDK["VISUALSTUDIO"] + vcdir_suffix + "bin"
  2275. binpath = os.path.join(vc_binpath, bindir)
  2276. if not os.path.isfile(binpath + "\\cl.exe"):
  2277. # Try the x86 tools, those should work just as well.
  2278. if arch == 'x64' and os.path.isfile(vc_binpath + "\\x86_amd64\\cl.exe"):
  2279. binpath = "{0}\\x86_amd64;{0}".format(vc_binpath)
  2280. elif winsdk_ver.startswith('10.'):
  2281. exit("Couldn't find compilers in %s. You may need to install the Windows SDK 7.1 and the Visual C++ 2010 SP1 Compiler Update for Windows SDK 7.1." % binpath)
  2282. else:
  2283. exit("Couldn't find compilers in %s." % binpath)
  2284. AddToPathEnv("PATH", binpath)
  2285. AddToPathEnv("PATH", SDK["VISUALSTUDIO"] + "Common7\\IDE")
  2286. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "include")
  2287. AddToPathEnv("INCLUDE", os.environ["VCINSTALLDIR"] + "atlmfc\\include")
  2288. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "lib\\" + libdir)
  2289. AddToPathEnv("LIB", os.environ["VCINSTALLDIR"] + "atlmfc\\lib\\" + libdir)
  2290. winsdk_ver = SDK["MSPLATFORM_VERSION"]
  2291. if winsdk_ver.startswith('10.'):
  2292. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2293. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + winsdk_ver + "\\" + arch)
  2294. # Windows Kit 10 introduces the "universal CRT".
  2295. inc_dir = SDK["MSPLATFORM"] + "Include\\" + winsdk_ver + "\\"
  2296. lib_dir = SDK["MSPLATFORM"] + "Lib\\" + winsdk_ver + "\\"
  2297. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2298. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2299. AddToPathEnv("INCLUDE", inc_dir + "um")
  2300. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2301. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2302. elif winsdk_ver == '8.1':
  2303. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin\\" + arch)
  2304. inc_dir = SDK["MSPLATFORM"] + "Include\\"
  2305. lib_dir = SDK["MSPLATFORM"] + "Lib\\winv6.3\\"
  2306. AddToPathEnv("INCLUDE", inc_dir + "shared")
  2307. AddToPathEnv("INCLUDE", inc_dir + "ucrt")
  2308. AddToPathEnv("INCLUDE", inc_dir + "um")
  2309. AddToPathEnv("LIB", lib_dir + "ucrt\\" + arch)
  2310. AddToPathEnv("LIB", lib_dir + "um\\" + arch)
  2311. else:
  2312. AddToPathEnv("PATH", SDK["MSPLATFORM"] + "bin")
  2313. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include")
  2314. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\atl")
  2315. AddToPathEnv("INCLUDE", SDK["MSPLATFORM"] + "include\\mfc")
  2316. if arch != 'x64':
  2317. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib")
  2318. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.CRT")
  2319. AddToPathEnv("PATH",SDK["VISUALSTUDIO"] + "VC\\redist\\x86\\Microsoft.VC100.MFC")
  2320. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\x64"):
  2321. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\x64")
  2322. elif os.path.isdir(SDK["MSPLATFORM"] + "lib\\amd64"):
  2323. AddToPathEnv("LIB", SDK["MSPLATFORM"] + "lib\\amd64")
  2324. else:
  2325. exit("Could not locate 64-bits libraries in Windows SDK directory!\nUsing directory: %s" % SDK["MSPLATFORM"])
  2326. # Targeting the 7.1 SDK (which is the only way to have Windows XP support)
  2327. # with Visual Studio 2015 requires use of the Universal CRT.
  2328. if winsdk_ver == '7.1' and SDK["VISUALSTUDIO_VERSION"] >= (14,0):
  2329. win_kit = GetRegistryKey("SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10")
  2330. # Fallback in case we can't read the registry.
  2331. if not win_kit or not os.path.isdir(win_kit):
  2332. win_kit = "C:\\Program Files (x86)\\Windows Kits\\10\\"
  2333. elif not win_kit.endswith('\\'):
  2334. win_kit += '\\'
  2335. AddToPathEnv("LIB", win_kit + "Lib\\10.0.10150.0\\ucrt\\" + arch)
  2336. AddToPathEnv("INCLUDE", win_kit + "Include\\10.0.10150.0\\ucrt")
  2337. # Copy the DLLs to the bin directory.
  2338. CopyAllFiles(GetOutputDir() + "/bin/", win_kit + "Redist\\ucrt\\DLLs\\" + arch + "\\")
  2339. ########################################################################
  2340. #
  2341. # Include and Lib directories.
  2342. #
  2343. # These allow you to add include and lib directories to the
  2344. # compiler search paths. These methods accept a "package"
  2345. # parameter, which specifies which package the directory is
  2346. # associated with. The include/lib directory is not used
  2347. # if the package is not selected. The package can be 'ALWAYS'.
  2348. #
  2349. ########################################################################
  2350. INCDIRECTORIES = []
  2351. LIBDIRECTORIES = []
  2352. FRAMEWORKDIRECTORIES = []
  2353. LIBNAMES = []
  2354. DEFSYMBOLS = []
  2355. def IncDirectory(opt, dir):
  2356. INCDIRECTORIES.append((opt, dir))
  2357. def LibDirectory(opt, dir):
  2358. LIBDIRECTORIES.append((opt, dir))
  2359. def FrameworkDirectory(opt, dir):
  2360. FRAMEWORKDIRECTORIES.append((opt, dir))
  2361. def LibName(opt, name):
  2362. # Check to see if the lib file actually exists for the thirdparty library given
  2363. # Are we a thirdparty library?
  2364. if name.startswith(GetThirdpartyDir()):
  2365. # Does this lib exist?
  2366. if not os.path.exists(name):
  2367. WARNINGS.append(name + " not found. Skipping Package " + opt)
  2368. if (opt in PkgListGet()):
  2369. if not PkgSkip(opt):
  2370. print("%sWARNING:%s Could not locate thirdparty package %s, excluding from build" % (GetColor("red"), GetColor(), opt.lower()))
  2371. PkgDisable(opt)
  2372. return
  2373. else:
  2374. print("%sERROR:%s Could not locate thirdparty package %s, aborting build" % (GetColor("red"), GetColor(), opt.lower()))
  2375. exit()
  2376. LIBNAMES.append((opt, name))
  2377. def DefSymbol(opt, sym, val=""):
  2378. DEFSYMBOLS.append((opt, sym, val))
  2379. ########################################################################
  2380. #
  2381. # This subroutine prepares the environment for the build.
  2382. #
  2383. ########################################################################
  2384. def SetupBuildEnvironment(compiler):
  2385. if GetVerbose():
  2386. print("Using compiler: %s" % compiler)
  2387. print("Host OS: %s" % GetHost())
  2388. print("Host arch: %s" % GetHostArch())
  2389. target = GetTarget()
  2390. if target != 'android':
  2391. print("Target OS: %s" % GetTarget())
  2392. else:
  2393. print("Target OS: %s (API level %d)" % (GetTarget(), ANDROID_API))
  2394. print("Target arch: %s" % GetTargetArch())
  2395. # Set to English so we can safely parse the result of gcc commands.
  2396. # Setting it to UTF-8 is necessary for Python 3 modules to import
  2397. # correctly.
  2398. os.environ["LC_ALL"] = "en_US.UTF-8"
  2399. os.environ["LANGUAGE"] = "en"
  2400. # In the case of Android, we have to put the toolchain on the PATH in order to use it.
  2401. if GetTarget() == 'android' and GetHost() != 'android':
  2402. AddToPathEnv("PATH", os.path.join(SDK["ANDROID_TOOLCHAIN"], "bin"))
  2403. if compiler == "MSVC":
  2404. # Add the visual studio tools to PATH et al.
  2405. SetupVisualStudioEnviron()
  2406. if compiler == "GCC":
  2407. # Invoke gcc to determine the system library directories.
  2408. global SYS_LIB_DIRS, SYS_INC_DIRS
  2409. if sys.platform == "darwin":
  2410. # We need to add this one explicitly for some reason.
  2411. SYS_LIB_DIRS.append(SDK["MACOSX"] + "/usr/lib")
  2412. if not SDK.get("MACOSX"):
  2413. # gcc doesn't add this one, but we do want it:
  2414. local_lib = SDK.get("SYSROOT", "") + "/usr/local/lib"
  2415. if os.path.isdir(local_lib):
  2416. SYS_LIB_DIRS.append(local_lib)
  2417. sysroot_flag = ""
  2418. if SDK.get("MACOSX"):
  2419. # The default compiler in Leopard does not respect --sysroot correctly.
  2420. sysroot_flag = " -isysroot " + SDK["MACOSX"]
  2421. if SDK.get("SYSROOT"):
  2422. sysroot_flag = ' --sysroot=%s -no-canonical-prefixes' % (SDK["SYSROOT"])
  2423. # Extract the dirs from the line that starts with 'libraries: ='.
  2424. cmd = GetCXX() + " -print-search-dirs" + sysroot_flag
  2425. handle = os.popen(cmd)
  2426. for line in handle:
  2427. if not line.startswith('libraries: ='):
  2428. continue
  2429. line = line[12:].strip()
  2430. libdirs = line.split(':')
  2431. while libdirs:
  2432. libdir = os.path.normpath(libdirs.pop(0))
  2433. if os.path.isdir(libdir):
  2434. if libdir not in SYS_LIB_DIRS:
  2435. SYS_LIB_DIRS.append(libdir)
  2436. elif len(libdir) == 1:
  2437. # Oops, is this a drive letter? Prepend it to the next.
  2438. libdirs[0] = libdir + ':' + libdirs[0]
  2439. elif GetVerbose():
  2440. print("Ignoring non-existent library directory %s" % (libdir))
  2441. returnval = handle.close()
  2442. if returnval != None and returnval != 0:
  2443. print("%sWARNING:%s %s failed" % (GetColor("red"), GetColor(), cmd))
  2444. SYS_LIB_DIRS += [SDK.get("SYSROOT", "") + "/usr/lib"]
  2445. # Now extract the preprocessor's include directories.
  2446. cmd = GetCXX() + sysroot_flag + " -x c++ -v -E /dev/null"
  2447. null = open(os.devnull, 'w')
  2448. handle = subprocess.Popen(cmd, stdout=null, stderr=subprocess.PIPE, shell=True)
  2449. scanning = False
  2450. for line in handle.communicate()[1].splitlines():
  2451. line = line.decode('utf-8', 'replace')
  2452. # Start looking at a line that says: #include "..." search starts here
  2453. if not scanning:
  2454. if line.startswith('#include'):
  2455. scanning = True
  2456. continue
  2457. if not line.startswith(' /'):
  2458. continue
  2459. line = line.strip()
  2460. if line.endswith(" (framework directory)"):
  2461. pass
  2462. elif os.path.isdir(line):
  2463. SYS_INC_DIRS.append(os.path.normpath(line))
  2464. elif GetVerbose():
  2465. print("Ignoring non-existent include directory %s" % (line))
  2466. if handle.returncode != 0 or not SYS_INC_DIRS:
  2467. print("%sWARNING:%s %s failed or did not produce the expected result" % (GetColor("red"), GetColor(), cmd))
  2468. sysroot = SDK.get("SYSROOT", "")
  2469. # Add some sensible directories as a fallback.
  2470. SYS_INC_DIRS = [
  2471. sysroot + "/usr/include",
  2472. sysroot + "/usr/local/include"
  2473. ]
  2474. pcbsd_inc = sysroot + "/usr/PCBSD/local/include"
  2475. if os.path.isdir(pcbsd_inc):
  2476. SYS_INC_DIRS.append(pcbsd_inc)
  2477. null.close()
  2478. # Print out the search paths
  2479. if GetVerbose():
  2480. print("System library search path:")
  2481. for dir in SYS_LIB_DIRS:
  2482. print(" " + dir)
  2483. print("System include search path:")
  2484. for dir in SYS_INC_DIRS:
  2485. print(" " + dir)
  2486. # If we're cross-compiling, no point in putting our output dirs on the path.
  2487. if CrossCompiling():
  2488. return
  2489. # Add our output directories to the environment.
  2490. builtdir = GetOutputDir()
  2491. AddToPathEnv("PYTHONPATH", builtdir)
  2492. AddToPathEnv("PANDA_PRC_DIR", os.path.join(builtdir, "etc"))
  2493. AddToPathEnv("PATH", os.path.join(builtdir, "bin"))
  2494. if GetHost() == 'windows':
  2495. # extension_native_helpers.py currently expects to find libpandaexpress on sys.path.
  2496. AddToPathEnv("PYTHONPATH", os.path.join(builtdir, "bin"))
  2497. AddToPathEnv("PATH", os.path.join(builtdir, "plugins"))
  2498. # Now for the special (DY)LD_LIBRARY_PATH on Unix-esque systems.
  2499. if GetHost() != 'windows':
  2500. # Get the current
  2501. ldpath = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep)
  2502. if GetHost() == 'darwin':
  2503. dyldpath = os.environ.get("DYLD_LIBRARY_PATH", "").split(os.pathsep)
  2504. # Remove any potential current Panda installation lib dirs
  2505. for i in ldpath[:]:
  2506. if i.startswith("/usr/lib/panda3d") or \
  2507. i.startswith("/usr/local/panda"):
  2508. ldpath.remove(i)
  2509. if GetHost() == 'darwin':
  2510. for i in dyldpath[:]:
  2511. if i.startswith("/Applications/Panda3D") or \
  2512. i.startswith("/Developer/Panda3D"):
  2513. dyldpath.remove(i)
  2514. # Add built/lib/ to (DY)LD_LIBRARY_PATH
  2515. ldpath.insert(0, os.path.join(builtdir, 'lib'))
  2516. os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(ldpath)
  2517. if GetHost() == 'darwin':
  2518. dyldpath.insert(0, os.path.join(builtdir, 'lib'))
  2519. os.environ["DYLD_LIBRARY_PATH"] = os.pathsep.join(dyldpath)
  2520. # OS X 10.11 removed DYLD_LIBRARY_PATH, but we still need to pass
  2521. # on our lib directory to ppackage, so add it to PATH instead.
  2522. os.environ["PATH"] = os.path.join(builtdir, 'lib') + ':' + os.environ.get("PATH", "")
  2523. # Workaround around compile issue on PCBSD
  2524. if (os.path.exists("/usr/PCBSD")):
  2525. os.environ["LD_LIBRARY_PATH"] += os.pathsep + "/usr/PCBSD/local/lib"
  2526. ########################################################################
  2527. ##
  2528. ## Routines to copy files into the build tree
  2529. ##
  2530. ########################################################################
  2531. def CopyFile(dstfile, srcfile):
  2532. if dstfile[-1] == '/':
  2533. dstfile += os.path.basename(srcfile)
  2534. if NeedsBuild([dstfile], [srcfile]):
  2535. if os.path.islink(srcfile):
  2536. # Preserve symlinks
  2537. if os.path.isfile(dstfile) or os.path.islink(dstfile):
  2538. print("Removing file %s" % (dstfile))
  2539. os.unlink(dstfile)
  2540. elif os.path.isdir(dstfile):
  2541. print("Removing directory %s" % (dstfile))
  2542. shutil.rmtree(dstfile)
  2543. os.symlink(os.readlink(srcfile), dstfile)
  2544. else:
  2545. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2546. if sys.platform == 'cygwin' and os.path.splitext(dstfile)[1].lower() in ('.dll', '.exe'):
  2547. os.chmod(dstfile, 0o755)
  2548. JustBuilt([dstfile], [srcfile])
  2549. def CopyAllFiles(dstdir, srcdir, suffix=""):
  2550. for x in GetDirectoryContents(srcdir, ["*"+suffix]):
  2551. CopyFile(dstdir + x, srcdir + x)
  2552. def CopyAllHeaders(dir, skip=[]):
  2553. for filename in GetDirectoryContents(dir, ["*.h", "*.I", "*.T"], skip):
  2554. srcfile = dir + "/" + filename
  2555. dstfile = OUTPUTDIR + "/include/" + filename
  2556. if (NeedsBuild([dstfile], [srcfile])):
  2557. WriteBinaryFile(dstfile, ReadBinaryFile(srcfile))
  2558. JustBuilt([dstfile], [srcfile])
  2559. def CopyTree(dstdir, srcdir, omitVCS=True):
  2560. if os.path.isdir(dstdir):
  2561. source_entries = os.listdir(srcdir)
  2562. for entry in source_entries:
  2563. srcpth = os.path.join(srcdir, entry)
  2564. dstpth = os.path.join(dstdir, entry)
  2565. if os.path.islink(srcpth) or os.path.isfile(srcpth):
  2566. if not omitVCS or entry not in VCS_FILES:
  2567. CopyFile(dstpth, srcpth)
  2568. else:
  2569. if not omitVCS or entry not in VCS_DIRS:
  2570. CopyTree(dstpth, srcpth)
  2571. # Delete files in dstdir that are not in srcdir.
  2572. for entry in os.listdir(dstdir):
  2573. if entry not in source_entries:
  2574. path = os.path.join(dstdir, entry)
  2575. if os.path.islink(path) or os.path.isfile(path):
  2576. os.remove(path)
  2577. elif os.path.isdir(path):
  2578. shutil.rmtree(path)
  2579. else:
  2580. if GetHost() == 'windows':
  2581. srcdir = srcdir.replace('/', '\\')
  2582. dstdir = dstdir.replace('/', '\\')
  2583. cmd = 'xcopy /I/Y/E/Q "' + srcdir + '" "' + dstdir + '"'
  2584. oscmd(cmd)
  2585. else:
  2586. if subprocess.call(['cp', '-R', '-f', srcdir, dstdir]) != 0:
  2587. exit("Copy failed.")
  2588. if omitVCS:
  2589. DeleteVCS(dstdir)
  2590. def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[], threads=0):
  2591. if (not os.path.isdir(dstdir)):
  2592. os.mkdir(dstdir)
  2593. lib2to3 = None
  2594. lib2to3_args = ['-w', '-n', '--no-diffs']
  2595. if len(lib2to3_fixers) > 0 and sys.version_info >= (3, 0):
  2596. from lib2to3.main import main as lib2to3
  2597. if lib2to3_fixers == ['all']:
  2598. lib2to3_args += ['-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma']
  2599. else:
  2600. for fixer in lib2to3_fixers:
  2601. lib2to3_args += ['-f', fixer]
  2602. if threads:
  2603. lib2to3_args += ['-j', str(threads)]
  2604. exclude_files = set(VCS_FILES)
  2605. exclude_files.add('panda3d.py')
  2606. refactor = []
  2607. for entry in os.listdir(srcdir):
  2608. srcpth = os.path.join(srcdir, entry)
  2609. dstpth = os.path.join(dstdir, entry)
  2610. if os.path.isfile(srcpth):
  2611. base, ext = os.path.splitext(entry)
  2612. if entry not in exclude_files and ext not in SUFFIX_INC + ['.pyc', '.pyo']:
  2613. if (NeedsBuild([dstpth], [srcpth])):
  2614. WriteBinaryFile(dstpth, ReadBinaryFile(srcpth))
  2615. if ext == '.py' and not entry.endswith('-extensions.py'):
  2616. refactor.append((dstpth, srcpth))
  2617. lib2to3_args.append(dstpth)
  2618. else:
  2619. JustBuilt([dstpth], [srcpth])
  2620. elif entry not in VCS_DIRS:
  2621. CopyPythonTree(dstpth, srcpth, lib2to3_fixers, threads=threads)
  2622. if refactor and lib2to3 is not None:
  2623. ret = lib2to3("lib2to3.fixes", lib2to3_args)
  2624. if ret != 0:
  2625. for dstpth, srcpth in refactor:
  2626. os.remove(dstpth)
  2627. exit("Error in lib2to3.")
  2628. else:
  2629. for dstpth, srcpth in refactor:
  2630. JustBuilt([dstpth], [srcpth])
  2631. ########################################################################
  2632. ##
  2633. ## Parse PandaVersion.pp to extract the version number.
  2634. ##
  2635. ########################################################################
  2636. cfg_parser = None
  2637. def GetMetadataValue(key):
  2638. global cfg_parser
  2639. if not cfg_parser:
  2640. # Parse the metadata from the setup.cfg file.
  2641. cfg_parser = configparser.ConfigParser()
  2642. path = os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')
  2643. assert cfg_parser.read(path), "Could not read setup.cfg file."
  2644. value = cfg_parser.get('metadata', key)
  2645. if key == 'classifiers':
  2646. value = value.strip().split('\n')
  2647. return value
  2648. # This function is being phased out.
  2649. def ParsePandaVersion(fn):
  2650. try:
  2651. f = open(fn, "r")
  2652. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+PANDA_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2653. for line in f:
  2654. match = pattern.match(line, 0)
  2655. if (match):
  2656. f.close()
  2657. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2658. f.close()
  2659. except: pass
  2660. return "0.0.0"
  2661. def ParsePluginVersion(fn):
  2662. try:
  2663. f = open(fn, "r")
  2664. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_PLUGIN_VERSION[ \t]+([0-9]+)[ \t]+([0-9]+)[ \t]+([0-9]+)')
  2665. for line in f:
  2666. match = pattern.match(line,0)
  2667. if (match):
  2668. f.close()
  2669. return match.group(1) + "." + match.group(2) + "." + match.group(3)
  2670. f.close()
  2671. except: pass
  2672. return "0.0.0"
  2673. def ParseCoreapiVersion(fn):
  2674. try:
  2675. f = open(fn, "r")
  2676. pattern = re.compile('^[ \t]*[#][ \t]*define[ \t]+P3D_COREAPI_VERSION.*([0-9]+)[ \t]*$')
  2677. for line in f:
  2678. match = pattern.match(line,0)
  2679. if (match):
  2680. f.close()
  2681. return match.group(1)
  2682. f.close()
  2683. except: pass
  2684. return "0"
  2685. ##########################################################################################
  2686. #
  2687. # Utility function to generate a resource file
  2688. #
  2689. ##########################################################################################
  2690. RESOURCE_FILE_TEMPLATE = """VS_VERSION_INFO VERSIONINFO
  2691. FILEVERSION %(commaversion)s
  2692. PRODUCTVERSION %(commaversion)s
  2693. FILEFLAGSMASK 0x3fL
  2694. FILEFLAGS %(debugflag)s
  2695. FILEOS 0x40004L
  2696. FILETYPE 0x2L
  2697. FILESUBTYPE 0x0L
  2698. BEGIN
  2699. BLOCK "StringFileInfo"
  2700. BEGIN
  2701. BLOCK "040904e4"
  2702. BEGIN
  2703. VALUE "FileDescription", "%(description)s\\0"
  2704. VALUE "FileVersion", "%(dotversion)s"
  2705. VALUE "LegalTrademarks", "\\0"
  2706. VALUE "MIMEType", "%(mimetype)s\\0"
  2707. VALUE "FileExtents", "%(extension)s\\0"
  2708. VALUE "FileOpenName", "%(filedesc)s\\0"
  2709. VALUE "OLESelfRegister", "\\0"
  2710. VALUE "OriginalFilename", "%(filename)s\\0"
  2711. VALUE "ProductName", "%(name)s %(version)s\\0"
  2712. VALUE "ProductVersion", "%(dotversion)s"
  2713. END
  2714. END
  2715. BLOCK "VarFileInfo"
  2716. BEGIN
  2717. VALUE "Translation", 0x409, 1252
  2718. END
  2719. END
  2720. """
  2721. def GenerateResourceFile(**kwargs):
  2722. if "debugflag" not in kwargs:
  2723. if GetOptimize() <= 2:
  2724. kwargs["debugflag"] = "0x1L"
  2725. else:
  2726. kwargs["debugflag"] = "0x0L"
  2727. kwargs["dotversion"] = kwargs["version"]
  2728. if len(kwargs["dotversion"].split(".")) == 3:
  2729. kwargs["dotversion"] += ".0"
  2730. if "commaversion" not in kwargs:
  2731. kwargs["commaversion"] = kwargs["dotversion"].replace(".", ",")
  2732. rcdata = ""
  2733. if not "noinclude" in kwargs:
  2734. rcdata += "#define APSTUDIO_READONLY_SYMBOLS\n"
  2735. rcdata += "#include \"winresrc.h\"\n"
  2736. rcdata += "#undef APSTUDIO_READONLY_SYMBOLS\n"
  2737. rcdata += RESOURCE_FILE_TEMPLATE % kwargs
  2738. if "icon" in kwargs:
  2739. rcdata += "\nICON_FILE ICON \"%s\"\n" % kwargs["icon"]
  2740. return rcdata
  2741. def WriteResourceFile(basename, **kwargs):
  2742. if not basename.endswith(".rc"):
  2743. basename += ".rc"
  2744. basename = GetOutputDir() + "/include/" + basename
  2745. ConditionalWriteFile(basename, GenerateResourceFile(**kwargs))
  2746. return basename
  2747. ########################################################################
  2748. ##
  2749. ## FindLocation
  2750. ##
  2751. ########################################################################
  2752. ORIG_EXT = {}
  2753. def GetOrigExt(x):
  2754. return ORIG_EXT[x]
  2755. def SetOrigExt(x, v):
  2756. ORIG_EXT[x] = v
  2757. def GetExtensionSuffix():
  2758. if sys.version_info >= (3, 0):
  2759. suffix = sysconfig.get_config_var('EXT_SUFFIX')
  2760. if suffix:
  2761. return suffix
  2762. target = GetTarget()
  2763. if target == 'windows':
  2764. return '.pyd'
  2765. else:
  2766. return '.so'
  2767. def CalcLocation(fn, ipath):
  2768. if fn.startswith("panda3d/") and fn.endswith(".py"):
  2769. return OUTPUTDIR + "/" + fn
  2770. if (fn.endswith(".class")):return OUTPUTDIR+"/classes/"+fn
  2771. if (fn.count("/")): return fn
  2772. dllext = ""
  2773. target = GetTarget()
  2774. if (GetOptimize() <= 2 and target == 'windows'): dllext = "_d"
  2775. if (fn == "AndroidManifest.xml"): return OUTPUTDIR+"/"+fn
  2776. if (fn.endswith(".cxx")): return CxxFindSource(fn, ipath)
  2777. if (fn.endswith(".I")): return CxxFindSource(fn, ipath)
  2778. if (fn.endswith(".h")): return CxxFindSource(fn, ipath)
  2779. if (fn.endswith(".c")): return CxxFindSource(fn, ipath)
  2780. if (fn.endswith(".py")): return CxxFindSource(fn, ipath)
  2781. if (fn.endswith(".yxx")): return CxxFindSource(fn, ipath)
  2782. if (fn.endswith(".lxx")): return CxxFindSource(fn, ipath)
  2783. if (fn.endswith(".pdef")):return CxxFindSource(fn, ipath)
  2784. if (fn.endswith(".xml")): return CxxFindSource(fn, ipath)
  2785. if (fn.endswith(".java")):return CxxFindSource(fn, ipath)
  2786. if (fn.endswith(".egg")): return OUTPUTDIR+"/models/"+fn
  2787. if (fn.endswith(".egg.pz")):return OUTPUTDIR+"/models/"+fn
  2788. if (fn.endswith(".pyd")): return OUTPUTDIR+"/panda3d/"+fn[:-4]+GetExtensionSuffix()
  2789. if (target == 'windows'):
  2790. if (fn.endswith(".def")): return CxxFindSource(fn, ipath)
  2791. if (fn.endswith(".rc")): return CxxFindSource(fn, ipath)
  2792. if (fn.endswith(".idl")): return CxxFindSource(fn, ipath)
  2793. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn
  2794. if (fn.endswith(".res")): return OUTPUTDIR+"/tmp/"+fn
  2795. if (fn.endswith(".tlb")): return OUTPUTDIR+"/tmp/"+fn
  2796. if (fn.endswith(".dll")): return OUTPUTDIR+"/bin/"+fn[:-4]+dllext+".dll"
  2797. if (fn.endswith(".ocx")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".ocx"
  2798. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".mll"
  2799. if (fn.endswith(".dlo")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dlo"
  2800. if (fn.endswith(".dli")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dli"
  2801. if (fn.endswith(".dle")): return OUTPUTDIR+"/plugins/"+fn[:-4]+dllext+".dle"
  2802. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".dll"
  2803. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn
  2804. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn
  2805. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+dllext+".lib"
  2806. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+dllext+".lib"
  2807. elif (target == 'darwin'):
  2808. if (fn.endswith(".mm")): return CxxFindSource(fn, ipath)
  2809. if (fn.endswith(".r")): return CxxFindSource(fn, ipath)
  2810. if (fn.endswith(".plist")): return CxxFindSource(fn, ipath)
  2811. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2812. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".dylib"
  2813. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2814. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2815. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2816. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2817. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2818. if (fn.endswith(".rsrc")): return OUTPUTDIR+"/tmp/"+fn
  2819. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn
  2820. if (fn.endswith(".app")): return OUTPUTDIR+"/bin/"+fn
  2821. else:
  2822. if (fn.endswith(".obj")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".o"
  2823. if (fn.endswith(".dll")): return OUTPUTDIR+"/lib/"+fn[:-4]+".so"
  2824. if (fn.endswith(".mll")): return OUTPUTDIR+"/plugins/"+fn
  2825. if (fn.endswith(".plugin")):return OUTPUTDIR+"/plugins/"+fn[:-7]+dllext+".so"
  2826. if (fn.endswith(".exe")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2827. if (fn.endswith(".p3d")): return OUTPUTDIR+"/bin/"+fn[:-4]
  2828. if (fn.endswith(".lib")): return OUTPUTDIR+"/lib/"+fn[:-4]+".a"
  2829. if (fn.endswith(".ilb")): return OUTPUTDIR+"/tmp/"+fn[:-4]+".a"
  2830. if (fn.endswith(".dat")): return OUTPUTDIR+"/tmp/"+fn
  2831. if (fn.endswith(".in")): return OUTPUTDIR+"/pandac/input/"+fn
  2832. return fn
  2833. def FindLocation(fn, ipath):
  2834. if (GetLinkAllStatic() and fn.endswith(".dll")):
  2835. fn = fn[:-4] + ".lib"
  2836. loc = CalcLocation(fn, ipath)
  2837. base, ext = os.path.splitext(fn)
  2838. ORIG_EXT[loc] = ext
  2839. return loc
  2840. ########################################################################
  2841. ##
  2842. ## TargetAdd
  2843. ##
  2844. ## Makepanda maintains a list of make-targets. Each target has
  2845. ## these attributes:
  2846. ##
  2847. ## name - the name of the file being created.
  2848. ## ext - the original file extension, prior to OS-specific translation
  2849. ## inputs - the names of the input files to the compiler
  2850. ## deps - other input files that the target also depends on
  2851. ## opts - compiler options, a catch-all category
  2852. ##
  2853. ## TargetAdd will create the target if it does not exist. Then,
  2854. ## depending on what options you pass, it will push data onto these
  2855. ## various target attributes. This is cumulative: for example, if
  2856. ## you use TargetAdd to add compiler options, then use TargetAdd
  2857. ## again with more compiler options, both sets of options will be
  2858. ## included.
  2859. ##
  2860. ## TargetAdd does some automatic dependency generation on C++ files.
  2861. ## It will scan these files for include-files and automatically push
  2862. ## the include files onto the list of dependencies. In order to do
  2863. ## this, it needs an include-file search path. So if you supply
  2864. ## any C++ input, you also need to supply compiler options containing
  2865. ## include-directories, or alternately, a separate ipath parameter.
  2866. ##
  2867. ## The main body of 'makepanda' is a long list of TargetAdd
  2868. ## directives building up a giant list of make targets. Then,
  2869. ## finally, the targets are run and panda is built.
  2870. ##
  2871. ## Makepanda's dependency system does not understand multiple
  2872. ## outputs from a single build step. When a build step generates
  2873. ## a primary output file and a secondary output file, it is
  2874. ## necessary to trick the dependency system. Insert a dummy
  2875. ## build step that "generates" the secondary output file, using
  2876. ## the primary output file as an input. There is a special
  2877. ## compiler option DEPENDENCYONLY that creates such a dummy
  2878. ## build-step. There are two cases where dummy build steps must
  2879. ## be inserted: bison generates an OBJ and a secondary header
  2880. ## file, interrogate generates an IN and a secondary IGATE.OBJ.
  2881. ##
  2882. ########################################################################
  2883. class Target:
  2884. pass
  2885. TARGET_LIST = []
  2886. TARGET_TABLE = {}
  2887. def TargetAdd(target, dummy=0, opts=[], input=[], dep=[], ipath=None, winrc=None):
  2888. if (dummy != 0):
  2889. exit("Syntax error in TargetAdd "+target)
  2890. if ipath is None: ipath = opts
  2891. if not ipath: ipath = []
  2892. if (type(input) == str): input = [input]
  2893. if (type(dep) == str): dep = [dep]
  2894. if os.path.splitext(target)[1] == '.pyd' and PkgSkip("PYTHON"):
  2895. # It makes no sense to build Python modules with python disabled.
  2896. return
  2897. full = FindLocation(target, [OUTPUTDIR + "/include"])
  2898. if (full not in TARGET_TABLE):
  2899. t = Target()
  2900. t.name = full
  2901. t.inputs = []
  2902. t.deps = {}
  2903. t.opts = []
  2904. TARGET_TABLE[full] = t
  2905. TARGET_LIST.append(t)
  2906. else:
  2907. t = TARGET_TABLE[full]
  2908. for x in opts:
  2909. if x not in t.opts:
  2910. t.opts.append(x)
  2911. ipath = [OUTPUTDIR + "/tmp"] + GetListOption(ipath, "DIR:") + [OUTPUTDIR+"/include"]
  2912. for x in input:
  2913. fullinput = FindLocation(x, ipath)
  2914. t.inputs.append(fullinput)
  2915. # Don't re-link a library or binary if just its dependency dlls have been altered.
  2916. # This should work out fine in most cases, and often reduces recompilation time.
  2917. if (os.path.splitext(x)[-1] not in SUFFIX_DLL):
  2918. t.deps[fullinput] = 1
  2919. (base,suffix) = os.path.splitext(x)
  2920. if (SUFFIX_INC.count(suffix)):
  2921. for d in CxxCalcDependencies(fullinput, ipath, []):
  2922. t.deps[d] = 1
  2923. elif suffix == '.java':
  2924. for d in JavaCalcDependencies(fullinput, OUTPUTDIR + "/classes"):
  2925. t.deps[d] = 1
  2926. # If we are linking statically, add the source DLL's dynamic dependencies.
  2927. if GetLinkAllStatic() and ORIG_EXT[fullinput] == '.lib' and fullinput in TARGET_TABLE:
  2928. tdep = TARGET_TABLE[fullinput]
  2929. for y in tdep.inputs:
  2930. if ORIG_EXT[y] == '.lib':
  2931. t.inputs.append(y)
  2932. for opt, _ in LIBNAMES + LIBDIRECTORIES + FRAMEWORKDIRECTORIES:
  2933. if opt in tdep.opts and opt not in t.opts:
  2934. t.opts.append(opt)
  2935. if x.endswith(".in"):
  2936. # Mark the _igate.cxx file as a dependency also.
  2937. outbase = os.path.basename(x)[:-3]
  2938. woutc = GetOutputDir()+"/tmp/"+outbase+"_igate.cxx"
  2939. t.deps[woutc] = 1
  2940. if target.endswith(".in"):
  2941. # Add any .N files.
  2942. base, ext = os.path.splitext(fullinput)
  2943. fulln = base + ".N"
  2944. if os.path.isfile(fulln):
  2945. t.deps[fulln] = 1
  2946. for x in dep:
  2947. fulldep = FindLocation(x, ipath)
  2948. t.deps[fulldep] = 1
  2949. if winrc and GetTarget() == 'windows':
  2950. TargetAdd(target, input=WriteResourceFile(target.split("/")[-1].split(".")[0], **winrc))
  2951. if target.endswith(".in"):
  2952. if not CrossCompiling():
  2953. t.deps[FindLocation("interrogate.exe", [])] = 1
  2954. t.deps[FindLocation("dtool_have_python.dat", [])] = 1
  2955. if target.endswith(".obj") and any(x.endswith(".in") for x in input):
  2956. if not CrossCompiling():
  2957. t.deps[FindLocation("interrogate_module.exe", [])] = 1
  2958. if target.endswith(".pz") and not CrossCompiling():
  2959. t.deps[FindLocation("pzip.exe", [])] = 1