makepandacore.py 136 KB

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